diff --git a/packages/backend/.gitignore b/packages/backend/.gitignore new file mode 100644 index 0000000000..c4653682cf --- /dev/null +++ b/packages/backend/.gitignore @@ -0,0 +1,7 @@ +# +*.profraw +*.profdata + +# rust build dir +target/ + diff --git a/packages/backend/.mocharc.json b/packages/backend/.mocharc.json deleted file mode 100644 index f836f9e900..0000000000 --- a/packages/backend/.mocharc.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extension": ["ts","js","cjs","mjs"], - "node-option": [ - "experimental-specifier-resolution=node", - "loader=./test/loader.js" - ], - "slow": 1000, - "timeout": 30000, - "exit": true -} diff --git a/packages/backend/.swcrc b/packages/backend/.swcrc deleted file mode 100644 index 39e112ff7c..0000000000 --- a/packages/backend/.swcrc +++ /dev/null @@ -1,25 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/swcrc", - "jsc": { - "parser": { - "syntax": "typescript", - "dynamicImport": true, - "decorators": true - }, - "transform": { - "legacyDecorator": true, - "decoratorMetadata": true - }, - "experimental": { - "keepImportAssertions": true - }, - "baseUrl": ".", - "paths": { - "@/*": [ - "./src/*" - ] - }, - "target": "es2022" - }, - "minify": false -} diff --git a/packages/backend/.vim/coc-settings.json b/packages/backend/.vim/coc-settings.json new file mode 100644 index 0000000000..b5c02503fb --- /dev/null +++ b/packages/backend/.vim/coc-settings.json @@ -0,0 +1,5 @@ +{ + "workspace.workspaceFolderCheckCwd": false, + "rust-analyzer.check.command": "clippy", + "rust-analyzer.check.extraArgs": "--profile test" +} diff --git a/packages/backend/Cargo.lock b/packages/backend/Cargo.lock new file mode 100644 index 0000000000..76277eac5c --- /dev/null +++ b/packages/backend/Cargo.lock @@ -0,0 +1,14 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "backend" +version = "0.0.0" +dependencies = [ + "server", +] + +[[package]] +name = "server" +version = "0.1.0" diff --git a/packages/backend/Cargo.toml b/packages/backend/Cargo.toml new file mode 100644 index 0000000000..893418cbcd --- /dev/null +++ b/packages/backend/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "backend" +version = "0.0.0" +edition = "2021" +default-run = "backend" + +[workspace] + +members = ["crates/*"] + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +server = { path = "crates/server" } + +[dev-dependencies] diff --git a/packages/backend/crates/server/Cargo.toml b/packages/backend/crates/server/Cargo.toml new file mode 100644 index 0000000000..dd022ab514 --- /dev/null +++ b/packages/backend/crates/server/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "server" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/packages/backend/crates/server/src/lib.rs b/packages/backend/crates/server/src/lib.rs new file mode 100644 index 0000000000..9771df5f2e --- /dev/null +++ b/packages/backend/crates/server/src/lib.rs @@ -0,0 +1,15 @@ +pub fn add(left: usize, right: usize) -> usize { + todo!(); + left + right +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_works() { + let result = add(2, 2); + assert_eq!(result, 4); + } +} diff --git a/packages/backend/jsconfig.json b/packages/backend/jsconfig.json deleted file mode 100644 index 1230aadd12..0000000000 --- a/packages/backend/jsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "compilerOptions": { - "target": "es6", - "module": "commonjs", - "allowSyntheticDefaultImports": true - }, - "exclude": [ - "node_modules", - "jspm_packages", - "tmp", - "temp" - ] -} diff --git a/packages/backend/native-utils/.cargo/config.toml b/packages/backend/native-utils/.cargo/config.toml deleted file mode 100644 index 7ede30ee04..0000000000 --- a/packages/backend/native-utils/.cargo/config.toml +++ /dev/null @@ -1,3 +0,0 @@ -[target.aarch64-unknown-linux-musl] -linker = "aarch64-linux-musl-gcc" -rustflags = ["-C", "target-feature=-crt-static"] \ No newline at end of file diff --git a/packages/backend/native-utils/.gitignore b/packages/backend/native-utils/.gitignore deleted file mode 100644 index 78b75d55ad..0000000000 --- a/packages/backend/native-utils/.gitignore +++ /dev/null @@ -1,200 +0,0 @@ -# Created by https://www.toptal.com/developers/gitignore/api/node -# Edit at https://www.toptal.com/developers/gitignore?templates=node - -### Node ### -# Logs -logs -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -lerna-debug.log* - -# Diagnostic reports (https://nodejs.org/api/report.html) -report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json - -# Runtime data -pids -*.pid -*.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage -*.lcov - -# nyc test coverage -.nyc_output - -# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# Bower dependency directory (https://bower.io/) -bower_components - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (https://nodejs.org/api/addons.html) -build/Release - -# Dependency directories -node_modules/ -jspm_packages/ - -# TypeScript v1 declaration files -typings/ - -# TypeScript cache -*.tsbuildinfo - -# Optional npm cache directory -.npm - -# Optional eslint cache -.eslintcache - -# Microbundle cache -.rpt2_cache/ -.rts2_cache_cjs/ -.rts2_cache_es/ -.rts2_cache_umd/ - -# Optional REPL history -.node_repl_history - -# Output of 'npm pack' -*.tgz - -# Yarn Integrity file -.yarn-integrity - -# dotenv environment variables file -.env -.env.test - -# parcel-bundler cache (https://parceljs.org/) -.cache - -# Next.js build output -.next - -# Nuxt.js build / generate output -.nuxt -dist - -# Gatsby files -.cache/ -# Comment in the public line in if your project uses Gatsby and not Next.js -# https://nextjs.org/blog/next-9-1#public-directory-support -# public - -# vuepress build output -.vuepress/dist - -# Serverless directories -.serverless/ - -# FuseBox cache -.fusebox/ - -# DynamoDB Local files -.dynamodb/ - -# TernJS port file -.tern-port - -# Stores VSCode versions used for testing VSCode extensions -.vscode-test - -# End of https://www.toptal.com/developers/gitignore/api/node - -# Created by https://www.toptal.com/developers/gitignore/api/macos -# Edit at https://www.toptal.com/developers/gitignore?templates=macos - -### macOS ### -# General -.DS_Store -.AppleDouble -.LSOverride - -# Icon must end with two -Icon - - -# Thumbnails -._* - -# Files that might appear in the root of a volume -.DocumentRevisions-V100 -.fseventsd -.Spotlight-V100 -.TemporaryItems -.Trashes -.VolumeIcon.icns -.com.apple.timemachine.donotpresent - -# Directories potentially created on remote AFP share -.AppleDB -.AppleDesktop -Network Trash Folder -Temporary Items -.apdisk - -### macOS Patch ### -# iCloud generated files -*.icloud - -# End of https://www.toptal.com/developers/gitignore/api/macos - -# Created by https://www.toptal.com/developers/gitignore/api/windows -# Edit at https://www.toptal.com/developers/gitignore?templates=windows - -### Windows ### -# Windows thumbnail cache files -Thumbs.db -Thumbs.db:encryptable -ehthumbs.db -ehthumbs_vista.db - -# Dump file -*.stackdump - -# Folder config file -[Dd]esktop.ini - -# Recycle Bin used on file shares -$RECYCLE.BIN/ - -# Windows Installer files -*.cab -*.msi -*.msix -*.msm -*.msp - -# Windows shortcuts -*.lnk - -# End of https://www.toptal.com/developers/gitignore/api/windows - -# napi-rs generated files -built/ - -#Added by cargo - -/target -Cargo.lock - -.pnp.* -.yarn/* -!.yarn/patches -!.yarn/plugins -!.yarn/releases -!.yarn/sdks -!.yarn/versions - -*.node diff --git a/packages/backend/native-utils/.npmignore b/packages/backend/native-utils/.npmignore deleted file mode 100644 index ec144db2a7..0000000000 --- a/packages/backend/native-utils/.npmignore +++ /dev/null @@ -1,13 +0,0 @@ -target -Cargo.lock -.cargo -.github -npm -.eslintrc -.prettierignore -rustfmt.toml -yarn.lock -*.node -.yarn -__test__ -renovate.json diff --git a/packages/backend/native-utils/Cargo.toml b/packages/backend/native-utils/Cargo.toml deleted file mode 100644 index 4f7fb4c39a..0000000000 --- a/packages/backend/native-utils/Cargo.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -edition = "2021" -name = "native-utils" -version = "0.0.0" - -[lib] -crate-type = ["cdylib"] - -[dependencies] -# Default enable napi4 feature, see https://nodejs.org/api/n-api.html#node-api-version-matrix -napi = { version = "2.12.0", default-features = false, features = ["napi4"] } -napi-derive = "2.12.0" - -[build-dependencies] -napi-build = "2.0.1" - -[profile.release] -lto = true diff --git a/packages/backend/native-utils/__test__/index.spec.mjs b/packages/backend/native-utils/__test__/index.spec.mjs deleted file mode 100644 index 0d41e012dd..0000000000 --- a/packages/backend/native-utils/__test__/index.spec.mjs +++ /dev/null @@ -1,7 +0,0 @@ -import test from "ava"; - -import { sum } from "../index.js"; - -test("sum from native", (t) => { - t.is(sum(1, 2), 3); -}); diff --git a/packages/backend/native-utils/build.rs b/packages/backend/native-utils/build.rs deleted file mode 100644 index 1f866b6a3c..0000000000 --- a/packages/backend/native-utils/build.rs +++ /dev/null @@ -1,5 +0,0 @@ -extern crate napi_build; - -fn main() { - napi_build::setup(); -} diff --git a/packages/backend/native-utils/npm/android-arm-eabi/README.md b/packages/backend/native-utils/npm/android-arm-eabi/README.md deleted file mode 100644 index 10199cb8ec..0000000000 --- a/packages/backend/native-utils/npm/android-arm-eabi/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `native-utils-android-arm-eabi` - -This is the **armv7-linux-androideabi** binary for `native-utils` diff --git a/packages/backend/native-utils/npm/android-arm-eabi/package.json b/packages/backend/native-utils/npm/android-arm-eabi/package.json deleted file mode 100644 index b4404c410a..0000000000 --- a/packages/backend/native-utils/npm/android-arm-eabi/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "native-utils-android-arm-eabi", - "version": "0.0.0", - "os": [ - "android" - ], - "cpu": [ - "arm" - ], - "main": "native-utils.android-arm-eabi.node", - "files": [ - "native-utils.android-arm-eabi.node" - ], - "license": "MIT", - "engines": { - "node": ">= 10" - } -} \ No newline at end of file diff --git a/packages/backend/native-utils/npm/android-arm64/README.md b/packages/backend/native-utils/npm/android-arm64/README.md deleted file mode 100644 index c32c2fe710..0000000000 --- a/packages/backend/native-utils/npm/android-arm64/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `native-utils-android-arm64` - -This is the **aarch64-linux-android** binary for `native-utils` diff --git a/packages/backend/native-utils/npm/android-arm64/package.json b/packages/backend/native-utils/npm/android-arm64/package.json deleted file mode 100644 index 9050ef37bd..0000000000 --- a/packages/backend/native-utils/npm/android-arm64/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "native-utils-android-arm64", - "version": "0.0.0", - "os": [ - "android" - ], - "cpu": [ - "arm64" - ], - "main": "native-utils.android-arm64.node", - "files": [ - "native-utils.android-arm64.node" - ], - "license": "MIT", - "engines": { - "node": ">= 10" - } -} \ No newline at end of file diff --git a/packages/backend/native-utils/npm/darwin-arm64/README.md b/packages/backend/native-utils/npm/darwin-arm64/README.md deleted file mode 100644 index 8703902223..0000000000 --- a/packages/backend/native-utils/npm/darwin-arm64/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `native-utils-darwin-arm64` - -This is the **aarch64-apple-darwin** binary for `native-utils` diff --git a/packages/backend/native-utils/npm/darwin-arm64/package.json b/packages/backend/native-utils/npm/darwin-arm64/package.json deleted file mode 100644 index a7fcef289f..0000000000 --- a/packages/backend/native-utils/npm/darwin-arm64/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "native-utils-darwin-arm64", - "version": "0.0.0", - "os": [ - "darwin" - ], - "cpu": [ - "arm64" - ], - "main": "native-utils.darwin-arm64.node", - "files": [ - "native-utils.darwin-arm64.node" - ], - "license": "MIT", - "engines": { - "node": ">= 10" - } -} \ No newline at end of file diff --git a/packages/backend/native-utils/npm/darwin-universal/README.md b/packages/backend/native-utils/npm/darwin-universal/README.md deleted file mode 100644 index 098bb35906..0000000000 --- a/packages/backend/native-utils/npm/darwin-universal/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `native-utils-darwin-universal` - -This is the **universal-apple-darwin** binary for `native-utils` diff --git a/packages/backend/native-utils/npm/darwin-universal/package.json b/packages/backend/native-utils/npm/darwin-universal/package.json deleted file mode 100644 index a46061d421..0000000000 --- a/packages/backend/native-utils/npm/darwin-universal/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "native-utils-darwin-universal", - "version": "0.0.0", - "os": [ - "darwin" - ], - "main": "native-utils.darwin-universal.node", - "files": [ - "native-utils.darwin-universal.node" - ], - "license": "MIT", - "engines": { - "node": ">= 10" - } -} \ No newline at end of file diff --git a/packages/backend/native-utils/npm/darwin-x64/README.md b/packages/backend/native-utils/npm/darwin-x64/README.md deleted file mode 100644 index 0acf363352..0000000000 --- a/packages/backend/native-utils/npm/darwin-x64/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `native-utils-darwin-x64` - -This is the **x86_64-apple-darwin** binary for `native-utils` diff --git a/packages/backend/native-utils/npm/darwin-x64/package.json b/packages/backend/native-utils/npm/darwin-x64/package.json deleted file mode 100644 index 6bbcf1d232..0000000000 --- a/packages/backend/native-utils/npm/darwin-x64/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "native-utils-darwin-x64", - "version": "0.0.0", - "os": [ - "darwin" - ], - "cpu": [ - "x64" - ], - "main": "native-utils.darwin-x64.node", - "files": [ - "native-utils.darwin-x64.node" - ], - "license": "MIT", - "engines": { - "node": ">= 10" - } -} \ No newline at end of file diff --git a/packages/backend/native-utils/npm/freebsd-x64/README.md b/packages/backend/native-utils/npm/freebsd-x64/README.md deleted file mode 100644 index 2b74996de7..0000000000 --- a/packages/backend/native-utils/npm/freebsd-x64/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `native-utils-freebsd-x64` - -This is the **x86_64-unknown-freebsd** binary for `native-utils` diff --git a/packages/backend/native-utils/npm/freebsd-x64/package.json b/packages/backend/native-utils/npm/freebsd-x64/package.json deleted file mode 100644 index 654b8abf38..0000000000 --- a/packages/backend/native-utils/npm/freebsd-x64/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "native-utils-freebsd-x64", - "version": "0.0.0", - "os": [ - "freebsd" - ], - "cpu": [ - "x64" - ], - "main": "native-utils.freebsd-x64.node", - "files": [ - "native-utils.freebsd-x64.node" - ], - "license": "MIT", - "engines": { - "node": ">= 10" - } -} \ No newline at end of file diff --git a/packages/backend/native-utils/npm/linux-arm-gnueabihf/README.md b/packages/backend/native-utils/npm/linux-arm-gnueabihf/README.md deleted file mode 100644 index 2203036de0..0000000000 --- a/packages/backend/native-utils/npm/linux-arm-gnueabihf/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `native-utils-linux-arm-gnueabihf` - -This is the **armv7-unknown-linux-gnueabihf** binary for `native-utils` diff --git a/packages/backend/native-utils/npm/linux-arm-gnueabihf/package.json b/packages/backend/native-utils/npm/linux-arm-gnueabihf/package.json deleted file mode 100644 index 1e206c078d..0000000000 --- a/packages/backend/native-utils/npm/linux-arm-gnueabihf/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "native-utils-linux-arm-gnueabihf", - "version": "0.0.0", - "os": [ - "linux" - ], - "cpu": [ - "arm" - ], - "main": "native-utils.linux-arm-gnueabihf.node", - "files": [ - "native-utils.linux-arm-gnueabihf.node" - ], - "license": "MIT", - "engines": { - "node": ">= 10" - } -} \ No newline at end of file diff --git a/packages/backend/native-utils/npm/linux-arm64-gnu/README.md b/packages/backend/native-utils/npm/linux-arm64-gnu/README.md deleted file mode 100644 index ad3a9333f5..0000000000 --- a/packages/backend/native-utils/npm/linux-arm64-gnu/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `native-utils-linux-arm64-gnu` - -This is the **aarch64-unknown-linux-gnu** binary for `native-utils` diff --git a/packages/backend/native-utils/npm/linux-arm64-gnu/package.json b/packages/backend/native-utils/npm/linux-arm64-gnu/package.json deleted file mode 100644 index aa0b2a805f..0000000000 --- a/packages/backend/native-utils/npm/linux-arm64-gnu/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "native-utils-linux-arm64-gnu", - "version": "0.0.0", - "os": [ - "linux" - ], - "cpu": [ - "arm64" - ], - "main": "native-utils.linux-arm64-gnu.node", - "files": [ - "native-utils.linux-arm64-gnu.node" - ], - "license": "MIT", - "engines": { - "node": ">= 10" - }, - "libc": [ - "glibc" - ] -} \ No newline at end of file diff --git a/packages/backend/native-utils/npm/linux-arm64-musl/README.md b/packages/backend/native-utils/npm/linux-arm64-musl/README.md deleted file mode 100644 index df282532ff..0000000000 --- a/packages/backend/native-utils/npm/linux-arm64-musl/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `native-utils-linux-arm64-musl` - -This is the **aarch64-unknown-linux-musl** binary for `native-utils` diff --git a/packages/backend/native-utils/npm/linux-arm64-musl/package.json b/packages/backend/native-utils/npm/linux-arm64-musl/package.json deleted file mode 100644 index 99e9387ee6..0000000000 --- a/packages/backend/native-utils/npm/linux-arm64-musl/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "native-utils-linux-arm64-musl", - "version": "0.0.0", - "os": [ - "linux" - ], - "cpu": [ - "arm64" - ], - "main": "native-utils.linux-arm64-musl.node", - "files": [ - "native-utils.linux-arm64-musl.node" - ], - "license": "MIT", - "engines": { - "node": ">= 10" - }, - "libc": [ - "musl" - ] -} \ No newline at end of file diff --git a/packages/backend/native-utils/npm/linux-x64-gnu/README.md b/packages/backend/native-utils/npm/linux-x64-gnu/README.md deleted file mode 100644 index 52eea85aab..0000000000 --- a/packages/backend/native-utils/npm/linux-x64-gnu/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `native-utils-linux-x64-gnu` - -This is the **x86_64-unknown-linux-gnu** binary for `native-utils` diff --git a/packages/backend/native-utils/npm/linux-x64-gnu/package.json b/packages/backend/native-utils/npm/linux-x64-gnu/package.json deleted file mode 100644 index f99a5f664e..0000000000 --- a/packages/backend/native-utils/npm/linux-x64-gnu/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "native-utils-linux-x64-gnu", - "version": "0.0.0", - "os": [ - "linux" - ], - "cpu": [ - "x64" - ], - "main": "native-utils.linux-x64-gnu.node", - "files": [ - "native-utils.linux-x64-gnu.node" - ], - "license": "MIT", - "engines": { - "node": ">= 10" - }, - "libc": [ - "glibc" - ] -} \ No newline at end of file diff --git a/packages/backend/native-utils/npm/linux-x64-musl/README.md b/packages/backend/native-utils/npm/linux-x64-musl/README.md deleted file mode 100644 index 6664b23783..0000000000 --- a/packages/backend/native-utils/npm/linux-x64-musl/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `native-utils-linux-x64-musl` - -This is the **x86_64-unknown-linux-musl** binary for `native-utils` diff --git a/packages/backend/native-utils/npm/linux-x64-musl/package.json b/packages/backend/native-utils/npm/linux-x64-musl/package.json deleted file mode 100644 index 56b520fff4..0000000000 --- a/packages/backend/native-utils/npm/linux-x64-musl/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "native-utils-linux-x64-musl", - "version": "0.0.0", - "os": [ - "linux" - ], - "cpu": [ - "x64" - ], - "main": "native-utils.linux-x64-musl.node", - "files": [ - "native-utils.linux-x64-musl.node" - ], - "license": "MIT", - "engines": { - "node": ">= 10" - }, - "libc": [ - "musl" - ] -} \ No newline at end of file diff --git a/packages/backend/native-utils/npm/win32-arm64-msvc/README.md b/packages/backend/native-utils/npm/win32-arm64-msvc/README.md deleted file mode 100644 index 7aec7e0a55..0000000000 --- a/packages/backend/native-utils/npm/win32-arm64-msvc/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `native-utils-win32-arm64-msvc` - -This is the **aarch64-pc-windows-msvc** binary for `native-utils` diff --git a/packages/backend/native-utils/npm/win32-arm64-msvc/package.json b/packages/backend/native-utils/npm/win32-arm64-msvc/package.json deleted file mode 100644 index 865a771052..0000000000 --- a/packages/backend/native-utils/npm/win32-arm64-msvc/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "native-utils-win32-arm64-msvc", - "version": "0.0.0", - "os": [ - "win32" - ], - "cpu": [ - "arm64" - ], - "main": "native-utils.win32-arm64-msvc.node", - "files": [ - "native-utils.win32-arm64-msvc.node" - ], - "license": "MIT", - "engines": { - "node": ">= 10" - } -} \ No newline at end of file diff --git a/packages/backend/native-utils/npm/win32-ia32-msvc/README.md b/packages/backend/native-utils/npm/win32-ia32-msvc/README.md deleted file mode 100644 index 690de1975d..0000000000 --- a/packages/backend/native-utils/npm/win32-ia32-msvc/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `native-utils-win32-ia32-msvc` - -This is the **i686-pc-windows-msvc** binary for `native-utils` diff --git a/packages/backend/native-utils/npm/win32-ia32-msvc/package.json b/packages/backend/native-utils/npm/win32-ia32-msvc/package.json deleted file mode 100644 index 994eff12fd..0000000000 --- a/packages/backend/native-utils/npm/win32-ia32-msvc/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "native-utils-win32-ia32-msvc", - "version": "0.0.0", - "os": [ - "win32" - ], - "cpu": [ - "ia32" - ], - "main": "native-utils.win32-ia32-msvc.node", - "files": [ - "native-utils.win32-ia32-msvc.node" - ], - "license": "MIT", - "engines": { - "node": ">= 10" - } -} \ No newline at end of file diff --git a/packages/backend/native-utils/npm/win32-x64-msvc/README.md b/packages/backend/native-utils/npm/win32-x64-msvc/README.md deleted file mode 100644 index e34a5ff172..0000000000 --- a/packages/backend/native-utils/npm/win32-x64-msvc/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `native-utils-win32-x64-msvc` - -This is the **x86_64-pc-windows-msvc** binary for `native-utils` diff --git a/packages/backend/native-utils/npm/win32-x64-msvc/package.json b/packages/backend/native-utils/npm/win32-x64-msvc/package.json deleted file mode 100644 index 33b259b132..0000000000 --- a/packages/backend/native-utils/npm/win32-x64-msvc/package.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "native-utils-win32-x64-msvc", - "version": "0.0.0", - "os": [ - "win32" - ], - "cpu": [ - "x64" - ], - "main": "native-utils.win32-x64-msvc.node", - "files": [ - "native-utils.win32-x64-msvc.node" - ], - "license": "MIT", - "engines": { - "node": ">= 10" - } -} \ No newline at end of file diff --git a/packages/backend/native-utils/package.json b/packages/backend/native-utils/package.json deleted file mode 100644 index 787d1bd89f..0000000000 --- a/packages/backend/native-utils/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "native-utils", - "version": "0.0.0", - "main": "built/index.js", - "types": "built/index.d.ts", - "napi": { - "name": "native-utils", - "triples": { - "additional": [ - "aarch64-apple-darwin", - "aarch64-linux-android", - "aarch64-unknown-linux-gnu", - "aarch64-unknown-linux-musl", - "aarch64-pc-windows-msvc", - "armv7-unknown-linux-gnueabihf", - "x86_64-unknown-linux-musl", - "x86_64-unknown-freebsd", - "i686-pc-windows-msvc", - "armv7-linux-androideabi", - "universal-apple-darwin" - ] - } - }, - "license": "MIT", - "devDependencies": { - "@napi-rs/cli": "^2.15.0", - "ava": "^5.1.1" - }, - "ava": { - "timeout": "3m" - }, - "engines": { - "node": ">= 10" - }, - "scripts": { - "artifacts": "napi artifacts", - "build": "napi build --platform --release ./built/", - "build:debug": "napi build --platform", - "prepublishOnly": "napi prepublish -t npm", - "test": "ava", - "universal": "napi universal", - "version": "napi version" - } -} diff --git a/packages/backend/native-utils/rustfmt.toml b/packages/backend/native-utils/rustfmt.toml deleted file mode 100644 index cab5731eda..0000000000 --- a/packages/backend/native-utils/rustfmt.toml +++ /dev/null @@ -1,2 +0,0 @@ -tab_spaces = 2 -edition = "2021" diff --git a/packages/backend/native-utils/src/lib.rs b/packages/backend/native-utils/src/lib.rs deleted file mode 100644 index bc5b9fc7cf..0000000000 --- a/packages/backend/native-utils/src/lib.rs +++ /dev/null @@ -1,2 +0,0 @@ - -pub mod mastodon_api; diff --git a/packages/backend/native-utils/src/mastodon_api.rs b/packages/backend/native-utils/src/mastodon_api.rs deleted file mode 100644 index 36b4eb9849..0000000000 --- a/packages/backend/native-utils/src/mastodon_api.rs +++ /dev/null @@ -1,70 +0,0 @@ -use napi::{bindgen_prelude::*, Error, Status}; -use napi_derive::napi; - -static CHAR_COLLECTION: &str = "0123456789abcdefghijklmnopqrstuvwxyz"; - -// -- NAPI exports -- - -#[napi] -pub enum IdConvertType { - MastodonId, - CalckeyId, -} - -#[napi] -pub fn convert_id(in_id: String, id_convert_type: IdConvertType) -> napi::Result<String> { - use IdConvertType::*; - match id_convert_type { - MastodonId => { - let mut out: i64 = 0; - for (i, c) in in_id.to_lowercase().chars().rev().enumerate() { - out += num_from_char(c)? as i64 * 36_i64.pow(i as u32); - } - - Ok(out.to_string()) - } - CalckeyId => { - let mut input: i64 = match in_id.parse() { - Ok(s) => s, - Err(_) => { - return Err(Error::new( - Status::InvalidArg, - "Unable to parse ID as MasstodonId", - )) - } - }; - let mut out = String::new(); - - while input != 0 { - out.insert(0, char_from_num((input % 36) as u8)?); - input /= 36; - } - - Ok(out) - } - } -} - -// -- end -- - -#[inline(always)] -fn num_from_char(character: char) -> napi::Result<u8> { - for (i, c) in CHAR_COLLECTION.chars().enumerate() { - if c == character { - return Ok(i as u8); - } - } - - Err(Error::new( - Status::InvalidArg, - "Invalid character in parsed base36 id", - )) -} - -#[inline(always)] -fn char_from_num(number: u8) -> napi::Result<char> { - CHAR_COLLECTION - .chars() - .nth(number as usize) - .ok_or(Error::from_status(Status::Unknown)) -} diff --git a/packages/backend/ormconfig.js b/packages/backend/ormconfig.js deleted file mode 100644 index 5f85cead8a..0000000000 --- a/packages/backend/ormconfig.js +++ /dev/null @@ -1,15 +0,0 @@ -import { DataSource } from "typeorm"; -import config from "./built/config/index.js"; -import { entities } from "./built/db/postgre.js"; - -export default new DataSource({ - type: "postgres", - host: config.db.host, - port: config.db.port, - username: config.db.user, - password: config.db.pass, - database: config.db.db, - extra: config.db.extra, - entities: entities, - migrations: ["migration/*.js"], -}); diff --git a/packages/backend/package.json b/packages/backend/package.json index 442ef5e187..8e3c70e1ab 100644 --- a/packages/backend/package.json +++ b/packages/backend/package.json @@ -1,197 +1,15 @@ { "name": "backend", - "main": "./index.js", "private": true, "type": "module", "scripts": { - "start": "pnpm node ./built/index.js", + "start": "cargo run --profile $( [ ${NODE_ENV:=dev} = 'production' ] && echo 'release' || echo $NODE_ENV )", "start:test": "NODE_ENV=test pnpm node ./built/index.js", - "migrate": "typeorm migration:run -d ormconfig.js", + "check": "cargo check", + "migrate": "cargo run --bin migrate", + "build": "cargo build --profile $( [ ${NODE_ENV:=dev} = 'production' ] && echo 'release' || echo $NODE_ENV )", "revertmigration": "typeorm migration:revert -d ormconfig.js", - "check:connect": "node ./check_connect.js", - "build": "napi build --platform --release --cargo-cwd native-utils ./native-utils/built/ && pnpm swc src -d built -D", - "watch": "pnpm swc src -d built -D -w", - "lint": "pnpm rome check \"src/**/*.ts\"", - "mocha": "cross-env NODE_ENV=test TS_NODE_FILES=true TS_NODE_TRANSPILE_ONLY=true TS_NODE_PROJECT=\"./test/tsconfig.json\" mocha", - "test": "pnpm run mocha" - }, - "resolutions": { - "chokidar": "^3.3.1" - }, - "optionalDependencies": { - "@swc/core-android-arm64": "1.3.11", - "@tensorflow/tfjs-node": "3.21.1" - }, - "dependencies": { - "@bull-board/api": "^4.6.4", - "@bull-board/koa": "^4.6.4", - "@bull-board/ui": "^4.6.4", - "@calckey/megalodon": "5.1.24", - "@discordapp/twemoji": "14.0.2", - "@elastic/elasticsearch": "7.17.0", - "@koa/cors": "3.4.3", - "@koa/multer": "3.0.0", - "@koa/router": "9.0.1", - "@peertube/http-signature": "1.7.0", - "@redocly/openapi-core": "1.0.0-beta.120", - "@sinonjs/fake-timers": "9.1.2", - "@syuilo/aiscript": "0.11.1", - "@tensorflow/tfjs": "^4.2.0", - "ajv": "8.11.2", - "archiver": "5.3.1", - "argon2": "^0.30.3", - "autobind-decorator": "2.4.0", - "autolinker": "4.0.0", - "autwh": "0.1.0", - "aws-sdk": "2.1277.0", - "axios": "^1.3.2", - "bcryptjs": "2.4.3", - "blurhash": "1.1.5", - "bull": "4.10.2", - "cacheable-lookup": "7.0.0", - "calckey-js": "workspace:*", - "cbor": "8.1.0", - "chalk": "5.2.0", - "chalk-template": "0.4.0", - "chokidar": "3.5.3", - "cli-highlight": "2.1.11", - "color-convert": "2.0.1", - "content-disposition": "0.5.4", - "date-fns": "2.29.3", - "deep-email-validator": "0.1.21", - "escape-regexp": "0.0.1", - "feed": "4.2.2", - "file-type": "17.1.6", - "fluent-ffmpeg": "2.1.2", - "got": "12.5.3", - "hpagent": "0.1.2", - "ioredis": "5.2.4", - "ip-cidr": "3.0.11", - "is-svg": "4.3.2", - "js-yaml": "4.1.0", - "jsdom": "20.0.3", - "jsonld": "6.0.0", - "jsrsasign": "10.6.1", - "koa": "2.13.4", - "koa-body": "^6.0.1", - "koa-bodyparser": "4.3.0", - "koa-json-body": "5.3.0", - "koa-logger": "3.2.1", - "koa-mount": "4.0.0", - "koa-send": "5.0.1", - "koa-slow": "2.1.0", - "koa-views": "7.0.2", - "mfm-js": "0.23.2", - "mime-types": "2.1.35", - "multer": "1.4.4-lts.1", - "native-utils": "link:native-utils", - "nested-property": "4.0.0", - "node-fetch": "3.3.0", - "nodemailer": "6.8.0", - "nsfwjs": "2.4.2", - "oauth": "^0.10.0", - "os-utils": "0.0.14", - "parse5": "7.1.2", - "pg": "8.8.0", - "private-ip": "2.3.4", - "probe-image-size": "7.2.3", - "promise-limit": "2.7.0", - "punycode": "2.1.1", - "pureimage": "0.3.15", - "qrcode": "1.5.1", - "qs": "6.9.7", - "random-seed": "0.3.0", - "ratelimiter": "3.4.1", - "re2": "1.18.0", - "redis-lock": "0.1.4", - "reflect-metadata": "0.1.13", - "rename": "1.0.4", - "rndstr": "1.0.0", - "rss-parser": "3.12.0", - "sanitize-html": "2.8.1", - "seedrandom": "^3.0.5", - "semver": "7.3.8", - "sharp": "0.31.3", - "sonic-channel": "^1.3.1", - "speakeasy": "2.0.0", - "stringz": "2.1.0", - "summaly": "github:misskey-dev/summaly", - "syslog-pro": "1.0.0", - "systeminformation": "5.16.9", - "tesseract.js": "^3.0.3", - "tinycolor2": "1.5.2", - "tmp": "0.2.1", - "twemoji-parser": "14.0.0", - "typeorm": "0.3.11", - "ulid": "2.3.0", - "unzipper": "0.10.11", - "uuid": "9.0.0", - "web-push": "3.5.0", - "websocket": "1.0.34", - "xev": "3.0.2" - }, - "devDependencies": { - "@swc/cli": "^0.1.62", - "@swc/core": "^1.3.50", - "@types/bcryptjs": "2.4.2", - "@types/bull": "3.15.9", - "@types/cbor": "6.0.0", - "@types/escape-regexp": "0.0.1", - "@types/fluent-ffmpeg": "2.1.20", - "@types/js-yaml": "4.0.5", - "@types/jsdom": "20.0.1", - "@types/jsonld": "1.5.8", - "@types/jsrsasign": "10.5.4", - "@types/koa": "2.13.5", - "@types/koa-bodyparser": "4.3.10", - "@types/koa-cors": "0.0.2", - "@types/koa-favicon": "2.0.21", - "@types/koa-logger": "3.1.2", - "@types/koa-mount": "4.0.2", - "@types/koa-send": "4.1.3", - "@types/koa-views": "7.0.0", - "@types/koa__cors": "3.3.0", - "@types/koa__multer": "2.0.4", - "@types/koa__router": "8.0.11", - "@types/mocha": "9.1.1", - "@types/node": "18.11.18", - "@types/node-fetch": "3.0.3", - "@types/nodemailer": "6.4.7", - "@types/oauth": "0.9.1", - "@types/pug": "2.0.6", - "@types/punycode": "2.1.0", - "@types/qrcode": "1.5.0", - "@types/qs": "6.9.7", - "@types/random-seed": "0.3.3", - "@types/ratelimiter": "3.4.4", - "@types/redis": "4.0.11", - "@types/rename": "1.0.4", - "@types/sanitize-html": "2.8.0", - "@types/semver": "7.3.13", - "@types/sharp": "0.31.1", - "@types/sinonjs__fake-timers": "8.1.2", - "@types/speakeasy": "2.0.7", - "@types/tinycolor2": "1.4.3", - "@types/tmp": "0.2.3", - "@types/uuid": "8.3.4", - "@types/web-push": "3.3.2", - "@types/websocket": "1.0.5", - "@types/ws": "8.5.3", - "autobind-decorator": "2.4.0", - "cross-env": "7.0.3", - "eslint": "^8.31.0", - "execa": "6.1.0", - "json5": "2.2.3", - "json5-loader": "4.0.1", - "mocha": "10.2.0", - "pug": "3.0.2", - "strict-event-emitter-types": "2.0.0", - "swc-loader": "^0.2.3", - "ts-loader": "9.4.2", - "ts-node": "10.9.1", - "tsconfig-paths": "4.1.2", - "typescript": "4.9.4", - "webpack": "^5.75.0", - "ws": "8.11.0" + "lint": "cargo check", + "test": "cargo test --workspace" } } diff --git a/packages/backend/rust-toolchain b/packages/backend/rust-toolchain new file mode 100644 index 0000000000..bf867e0ae5 --- /dev/null +++ b/packages/backend/rust-toolchain @@ -0,0 +1 @@ +nightly diff --git a/packages/backend/rustfmt.toml b/packages/backend/rustfmt.toml new file mode 100644 index 0000000000..b196eaa2dc --- /dev/null +++ b/packages/backend/rustfmt.toml @@ -0,0 +1 @@ +tab_spaces = 2 diff --git a/packages/backend/src/@types/hcaptcha.d.ts b/packages/backend/src/@types/hcaptcha.d.ts deleted file mode 100644 index 21f65c678c..0000000000 --- a/packages/backend/src/@types/hcaptcha.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -declare module "hcaptcha" { - interface IVerifyResponse { - success: boolean; - challenge_ts: string; - hostname: string; - credit?: boolean; - "error-codes"?: unknown[]; - } - - export function verify( - secret: string, - token: string, - ): Promise<IVerifyResponse>; -} diff --git a/packages/backend/src/@types/http-signature.d.ts b/packages/backend/src/@types/http-signature.d.ts deleted file mode 100644 index 3bfece8cbf..0000000000 --- a/packages/backend/src/@types/http-signature.d.ts +++ /dev/null @@ -1,98 +0,0 @@ -declare module "@peertube/http-signature" { - import type { IncomingMessage, ClientRequest } from "node:http"; - - interface ISignature { - keyId: string; - algorithm: string; - headers: string[]; - signature: string; - } - - interface IOptions { - headers?: string[]; - algorithm?: string; - strict?: boolean; - authorizationHeaderName?: string; - } - - interface IParseRequestOptions extends IOptions { - clockSkew?: number; - } - - interface IParsedSignature { - scheme: string; - params: ISignature; - signingString: string; - algorithm: string; - keyId: string; - } - - type RequestSignerConstructorOptions = - | IRequestSignerConstructorOptionsFromProperties - | IRequestSignerConstructorOptionsFromFunction; - - interface IRequestSignerConstructorOptionsFromProperties { - keyId: string; - key: string | Buffer; - algorithm?: string; - } - - interface IRequestSignerConstructorOptionsFromFunction { - sign?: (data: string, cb: (err: any, sig: ISignature) => void) => void; - } - - class RequestSigner { - constructor(options: RequestSignerConstructorOptions); - - public writeHeader(header: string, value: string): string; - - public writeDateHeader(): string; - - public writeTarget(method: string, path: string): void; - - public sign(cb: (err: any, authz: string) => void): void; - } - - interface ISignRequestOptions extends IOptions { - keyId: string; - key: string; - httpVersion?: string; - } - - export function parse( - request: IncomingMessage, - options?: IParseRequestOptions, - ): IParsedSignature; - export function parseRequest( - request: IncomingMessage, - options?: IParseRequestOptions, - ): IParsedSignature; - - export function sign( - request: ClientRequest, - options: ISignRequestOptions, - ): boolean; - export function signRequest( - request: ClientRequest, - options: ISignRequestOptions, - ): boolean; - export function createSigner(): RequestSigner; - export function isSigner(obj: any): obj is RequestSigner; - - export function sshKeyToPEM(key: string): string; - export function sshKeyFingerprint(key: string): string; - export function pemToRsaSSHKey(pem: string, comment: string): string; - - export function verify( - parsedSignature: IParsedSignature, - pubkey: string | Buffer, - ): boolean; - export function verifySignature( - parsedSignature: IParsedSignature, - pubkey: string | Buffer, - ): boolean; - export function verifyHMAC( - parsedSignature: IParsedSignature, - secret: string, - ): boolean; -} diff --git a/packages/backend/src/@types/koa-json-body.d.ts b/packages/backend/src/@types/koa-json-body.d.ts deleted file mode 100644 index e5282d81bf..0000000000 --- a/packages/backend/src/@types/koa-json-body.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -declare module "koa-json-body" { - import type { Middleware } from "koa"; - - interface IKoaJsonBodyOptions { - strict: boolean; - limit: string; - fallback: boolean; - } - - function koaJsonBody(opt?: IKoaJsonBodyOptions): Middleware; - - namespace koaJsonBody {} // Hack - - export = koaJsonBody; -} diff --git a/packages/backend/src/@types/koa-remove-trailing-slashes/index.d.ts b/packages/backend/src/@types/koa-remove-trailing-slashes/index.d.ts deleted file mode 100644 index 429d1d53e0..0000000000 --- a/packages/backend/src/@types/koa-remove-trailing-slashes/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare module "koa-remove-trailing-slashes"; diff --git a/packages/backend/src/@types/koa-slow.d.ts b/packages/backend/src/@types/koa-slow.d.ts deleted file mode 100644 index e24be51e2a..0000000000 --- a/packages/backend/src/@types/koa-slow.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -declare module "koa-slow" { - import type { Middleware } from "koa"; - - interface ISlowOptions { - url?: RegExp; - delay?: number; - } - - function slow(options?: ISlowOptions): Middleware; - - namespace slow {} // Hack - - export = slow; -} diff --git a/packages/backend/src/@types/os-utils.d.ts b/packages/backend/src/@types/os-utils.d.ts deleted file mode 100644 index 504096ae2b..0000000000 --- a/packages/backend/src/@types/os-utils.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -declare module "os-utils" { - type FreeCommandCallback = (usedmem: number) => void; - - type HarddriveCallback = (total: number, free: number, used: number) => void; - - type GetProcessesCallback = (result: string) => void; - - type CPUCallback = (perc: number) => void; - - export function platform(): NodeJS.Platform; - export function cpuCount(): number; - export function sysUptime(): number; - export function processUptime(): number; - - export function freemem(): number; - export function totalmem(): number; - export function freememPercentage(): number; - export function freeCommand(callback: FreeCommandCallback): void; - - export function harddrive(callback: HarddriveCallback): void; - - export function getProcesses(callback: GetProcessesCallback): void; - export function getProcesses( - nProcess: number, - callback: GetProcessesCallback, - ): void; - - export function allLoadavg(): string; - export function loadavg(_time?: number): number; - - export function cpuFree(callback: CPUCallback): void; - export function cpuUsage(callback: CPUCallback): void; -} diff --git a/packages/backend/src/@types/package.json.d.ts b/packages/backend/src/@types/package.json.d.ts deleted file mode 100644 index d8ec636446..0000000000 --- a/packages/backend/src/@types/package.json.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -declare module "*/package.json" { - interface IRepository { - type: string; - url: string; - } - - export const name: string; - export const version: string; - export const repository: IRepository; -} diff --git a/packages/backend/src/@types/probe-image-size.d.ts b/packages/backend/src/@types/probe-image-size.d.ts deleted file mode 100644 index 4ed13df7fa..0000000000 --- a/packages/backend/src/@types/probe-image-size.d.ts +++ /dev/null @@ -1,37 +0,0 @@ -declare module "probe-image-size" { - import type { ReadStream } from "node:fs"; - - type ProbeOptions = { - retries: 1; - timeout: 30000; - }; - - type ProbeResult = { - width: number; - height: number; - length?: number; - type: string; - mime: string; - wUnits: "in" | "mm" | "cm" | "pt" | "pc" | "px" | "em" | "ex"; - hUnits: "in" | "mm" | "cm" | "pt" | "pc" | "px" | "em" | "ex"; - url?: string; - }; - - function probeImageSize( - src: string | ReadStream, - options?: ProbeOptions, - ): Promise<ProbeResult>; - function probeImageSize( - src: string | ReadStream, - callback: (err: Error | null, result?: ProbeResult) => void, - ): void; - function probeImageSize( - src: string | ReadStream, - options: ProbeOptions, - callback: (err: Error | null, result?: ProbeResult) => void, - ): void; - - namespace probeImageSize {} // Hack - - export = probeImageSize; -} diff --git a/packages/backend/src/bin/migrate.rs b/packages/backend/src/bin/migrate.rs new file mode 100644 index 0000000000..299db6482a --- /dev/null +++ b/packages/backend/src/bin/migrate.rs @@ -0,0 +1,4 @@ + +fn main() { + todo!(); +} diff --git a/packages/backend/src/boot/index.ts b/packages/backend/src/boot/index.ts deleted file mode 100644 index e4f2ed7b1b..0000000000 --- a/packages/backend/src/boot/index.ts +++ /dev/null @@ -1,89 +0,0 @@ -import cluster from "node:cluster"; -import chalk from "chalk"; -import Xev from "xev"; - -import Logger from "@/services/logger.js"; -import { envOption } from "../env.js"; - -// for typeorm -import "reflect-metadata"; -import { masterMain } from "./master.js"; -import { workerMain } from "./worker.js"; -import os from "node:os"; - -const logger = new Logger("core", "cyan"); -const clusterLogger = logger.createSubLogger("cluster", "orange", false); -const ev = new Xev(); - -/** - * Init process - */ -export default async function () { - process.title = `Calckey (${cluster.isPrimary ? "master" : "worker"})`; - - if (cluster.isPrimary || envOption.disableClustering) { - await masterMain(); - if (cluster.isPrimary) { - ev.mount(); - } - } - - if (cluster.isWorker || envOption.disableClustering) { - await workerMain(); - } - - if (cluster.isPrimary) { - // Leave the master process with a marginally lower priority but not too low. - os.setPriority(2); - } - if (cluster.isWorker) { - // Set workers to a much lower priority so that the master process will be - // able to respond to api calls even if the workers gank everything. - os.setPriority(10); - } - - // For when Calckey is started in a child process during unit testing. - // Otherwise, process.send cannot be used, so start it. - if (process.send) { - process.send("ok"); - } -} - -//#region Events - -// Listen new workers -cluster.on("fork", (worker) => { - clusterLogger.debug(`Process forked: [${worker.id}]`); -}); - -// Listen online workers -cluster.on("online", (worker) => { - clusterLogger.debug(`Process is now online: [${worker.id}]`); -}); - -// Listen for dying workers -cluster.on("exit", (worker) => { - // Replace the dead worker, - // we're not sentimental - clusterLogger.error(chalk.red(`[${worker.id}] died :(`)); - cluster.fork(); -}); - -// Display detail of unhandled promise rejection -if (!envOption.quiet) { - process.on("unhandledRejection", console.dir); -} - -// Display detail of uncaught exception -process.on("uncaughtException", (err) => { - try { - logger.error(err); - } catch {} -}); - -// Dying away... -process.on("exit", (code) => { - logger.info(`The process is going to exit with code ${code}`); -}); - -//#endregion diff --git a/packages/backend/src/boot/master.ts b/packages/backend/src/boot/master.ts deleted file mode 100644 index 193f02429d..0000000000 --- a/packages/backend/src/boot/master.ts +++ /dev/null @@ -1,189 +0,0 @@ -import * as fs from "node:fs"; -import { fileURLToPath } from "node:url"; -import { dirname } from "node:path"; -import * as os from "node:os"; -import cluster from "node:cluster"; -import chalk from "chalk"; -import chalkTemplate from "chalk-template"; -import semver from "semver"; - -import Logger from "@/services/logger.js"; -import loadConfig from "@/config/load.js"; -import type { Config } from "@/config/types.js"; -import { lessThan } from "@/prelude/array.js"; -import { envOption } from "../env.js"; -import { showMachineInfo } from "@/misc/show-machine-info.js"; -import { db, initDb } from "../db/postgre.js"; - -const _filename = fileURLToPath(import.meta.url); -const _dirname = dirname(_filename); - -const meta = JSON.parse( - fs.readFileSync(`${_dirname}/../../../../built/meta.json`, "utf-8"), -); - -const logger = new Logger("core", "cyan"); -const bootLogger = logger.createSubLogger("boot", "magenta", false); - -const themeColor = chalk.hex("#31748f"); - -function greet() { - if (!envOption.quiet) { - //#region Calckey logo - const v = `v${meta.version}`; - console.log(themeColor(" ___ _ _ ")); - console.log(themeColor(" / __\\__ _| | ___| | _____ _ _ ")); - console.log(themeColor(" / / / _` | |/ __| |/ / _ | | |")); - console.log(themeColor("/ /__| (_| | | (__| < __/ |_| |")); - console.log(themeColor("\\____/\\__,_|_|\\___|_|\\_\\___|\\__, |")); - console.log(themeColor(" (___/ ")); - //#endregion - - console.log( - " Calckey is an open-source decentralized microblogging platform.", - ); - console.log( - chalk.rgb( - 255, - 136, - 0, - )( - " If you like Calckey, please consider starring or contributing to the repo. https://codeberg.org/calckey/calckey", - ), - ); - - console.log(""); - console.log( - chalkTemplate`--- ${os.hostname()} {gray (PID: ${process.pid.toString()})} ---`, - ); - } - - bootLogger.info("Welcome to Calckey!"); - bootLogger.info(`Calckey v${meta.version}`, null, true); -} - -/** - * Init master process - */ -export async function masterMain() { - let config!: Config; - - // initialize app - try { - greet(); - showEnvironment(); - await showMachineInfo(bootLogger); - showNodejsVersion(); - config = loadConfigBoot(); - await connectDb(); - } catch (e) { - bootLogger.error("Fatal error occurred during initialization", null, true); - process.exit(1); - } - - bootLogger.succ("Calckey initialized"); - - if (!envOption.disableClustering) { - await spawnWorkers(config.clusterLimit); - } - - bootLogger.succ( - `Now listening on port ${config.port} on ${config.url}`, - null, - true, - ); - - if (!envOption.noDaemons) { - import("../daemons/server-stats.js").then((x) => x.default()); - import("../daemons/queue-stats.js").then((x) => x.default()); - import("../daemons/janitor.js").then((x) => x.default()); - } -} - -function showEnvironment(): void { - const env = process.env.NODE_ENV; - const logger = bootLogger.createSubLogger("env"); - logger.info( - typeof env === "undefined" ? "NODE_ENV is not set" : `NODE_ENV: ${env}`, - ); - - if (env !== "production") { - logger.warn("The environment is not in production mode."); - logger.warn("DO NOT USE FOR PRODUCTION PURPOSE!", null, true); - } -} - -function showNodejsVersion(): void { - const nodejsLogger = bootLogger.createSubLogger("nodejs"); - - nodejsLogger.info(`Version ${process.version} detected.`); - - const minVersion = fs - .readFileSync(`${_dirname}/../../../../.node-version`, "utf-8") - .trim(); - if (semver.lt(process.version, minVersion)) { - nodejsLogger.error(`At least Node.js ${minVersion} required!`); - process.exit(1); - } -} - -function loadConfigBoot(): Config { - const configLogger = bootLogger.createSubLogger("config"); - let config; - - try { - config = loadConfig(); - } catch (exception) { - if (exception.code === "ENOENT") { - configLogger.error("Configuration file not found", null, true); - process.exit(1); - } else if (e instanceof Error) { - configLogger.error(e.message); - process.exit(1); - } - throw exception; - } - - configLogger.succ("Loaded"); - - return config; -} - -async function connectDb(): Promise<void> { - const dbLogger = bootLogger.createSubLogger("db"); - - // Try to connect to DB - try { - dbLogger.info("Connecting..."); - await initDb(); - const v = await db - .query("SHOW server_version") - .then((x) => x[0].server_version); - dbLogger.succ(`Connected: v${v}`); - } catch (e) { - dbLogger.error("Cannot connect", null, true); - dbLogger.error(e); - process.exit(1); - } -} - -async function spawnWorkers(limit: number = 1) { - const workers = Math.min(limit, os.cpus().length); - bootLogger.info(`Starting ${workers} worker${workers === 1 ? "" : "s"}...`); - await Promise.all([...Array(workers)].map(spawnWorker)); - bootLogger.succ("All workers started"); -} - -function spawnWorker(): Promise<void> { - return new Promise((res) => { - const worker = cluster.fork(); - worker.on("message", (message) => { - if (message === "listenFailed") { - bootLogger.error("The server Listen failed due to the previous error."); - process.exit(1); - } - if (message !== "ready") return; - res(); - }); - }); -} diff --git a/packages/backend/src/boot/worker.ts b/packages/backend/src/boot/worker.ts deleted file mode 100644 index 70442b096e..0000000000 --- a/packages/backend/src/boot/worker.ts +++ /dev/null @@ -1,20 +0,0 @@ -import cluster from "node:cluster"; -import { initDb } from "../db/postgre.js"; - -/** - * Init worker process - */ -export async function workerMain() { - await initDb(); - - // start server - await import("../server/index.js").then((x) => x.default()); - - // start job queue - import("../queue/index.js").then((x) => x.default()); - - if (cluster.isWorker) { - // Send a 'ready' message to parent process - process.send!("ready"); - } -} diff --git a/packages/backend/src/config/index.ts b/packages/backend/src/config/index.ts deleted file mode 100644 index ae197b09ca..0000000000 --- a/packages/backend/src/config/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -import load from "./load.js"; - -export default load(); diff --git a/packages/backend/src/config/load.ts b/packages/backend/src/config/load.ts deleted file mode 100644 index 9b8ee5edbb..0000000000 --- a/packages/backend/src/config/load.ts +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Config loader - */ - -import * as fs from "node:fs"; -import { fileURLToPath } from "node:url"; -import { dirname } from "node:path"; -import * as yaml from "js-yaml"; -import type { Source, Mixin } from "./types.js"; - -const _filename = fileURLToPath(import.meta.url); -const _dirname = dirname(_filename); - -/** - * Path of configuration directory - */ -const dir = `${_dirname}/../../../../.config`; - -/** - * Path of configuration file - */ -const path = - process.env.NODE_ENV === "test" ? `${dir}/test.yml` : `${dir}/default.yml`; - -export default function load() { - const meta = JSON.parse( - fs.readFileSync(`${_dirname}/../../../../built/meta.json`, "utf-8"), - ); - const clientManifest = JSON.parse( - fs.readFileSync( - `${_dirname}/../../../../built/_client_dist_/manifest.json`, - "utf-8", - ), - ); - const config = yaml.load(fs.readFileSync(path, "utf-8")) as Source; - - const mixin = {} as Mixin; - - const url = tryCreateUrl(config.url); - - config.url = url.origin; - - config.port = config.port || parseInt(process.env.PORT || "", 10); - - mixin.version = meta.version; - mixin.host = url.host; - mixin.hostname = url.hostname; - mixin.scheme = url.protocol.replace(/:$/, ""); - mixin.wsScheme = mixin.scheme.replace("http", "ws"); - mixin.wsUrl = `${mixin.wsScheme}://${mixin.host}`; - mixin.apiUrl = `${mixin.scheme}://${mixin.host}/api`; - mixin.authUrl = `${mixin.scheme}://${mixin.host}/auth`; - mixin.driveUrl = `${mixin.scheme}://${mixin.host}/files`; - mixin.userAgent = `Calckey/${meta.version} (${config.url})`; - mixin.clientEntry = clientManifest["src/init.ts"]; - - if (!config.redis.prefix) config.redis.prefix = mixin.host; - - return Object.assign(config, mixin); -} - -function tryCreateUrl(url: string) { - try { - return new URL(url); - } catch (e) { - throw new Error(`url="${url}" is not a valid URL.`); - } -} diff --git a/packages/backend/src/config/types.ts b/packages/backend/src/config/types.ts deleted file mode 100644 index a7cdc89cf2..0000000000 --- a/packages/backend/src/config/types.ts +++ /dev/null @@ -1,133 +0,0 @@ -/** - * ユーザーが設定する必要のある情報 - */ -export type Source = { - repository_url?: string; - feedback_url?: string; - url: string; - port: number; - disableHsts?: boolean; - db: { - host: string; - port: number; - db: string; - user: string; - pass: string; - disableCache?: boolean; - extra?: { [x: string]: string }; - }; - redis: { - host: string; - port: number; - family?: number; - pass: string; - db?: number; - prefix?: string; - }; - elasticsearch: { - host: string; - port: number; - ssl?: boolean; - user?: string; - pass?: string; - index?: string; - }; - sonic: { - host: string; - port: number; - auth?: string; - collection?: string; - bucket?: string; - }; - - proxy?: string; - proxySmtp?: string; - proxyBypassHosts?: string[]; - - allowedPrivateNetworks?: string[]; - - maxFileSize?: number; - - accesslog?: string; - - clusterLimit?: number; - - id: string; - - outgoingAddressFamily?: "ipv4" | "ipv6" | "dual"; - - deliverJobConcurrency?: number; - inboxJobConcurrency?: number; - deliverJobPerSec?: number; - inboxJobPerSec?: number; - deliverJobMaxAttempts?: number; - inboxJobMaxAttempts?: number; - - syslog: { - host: string; - port: number; - }; - - mediaProxy?: string; - proxyRemoteFiles?: boolean; - - twa: { - nameSpace?: string; - packageName?: string; - sha256CertFingerprints?: string[]; - }; - - // Managed hosting stuff - maxUserSignups?: number; - isManagedHosting?: boolean; - maxNoteLength?: number; - maxCaptionLength?: number; - deepl: { - managed?: boolean; - authKey?: string; - isPro?: boolean; - }; - email: { - managed?: boolean; - address?: string; - host?: string; - port?: number; - user?: string; - pass?: string; - useImplicitSslTls?: boolean; - }; - objectStorage: { - managed?: boolean; - baseUrl?: string; - bucket?: string; - prefix?: string; - endpoint?: string; - region?: string; - accessKey?: string; - secretKey?: string; - useSsl?: boolean; - connnectOverProxy?: boolean; - setPublicReadOnUpload?: boolean; - s3ForcePathStyle?: boolean; - }; - summalyProxyUrl?: string; -}; - -/** - * Misskeyが自動的に(ユーザーが設定した情報から推論して)設定する情報 - */ -export type Mixin = { - version: string; - host: string; - hostname: string; - scheme: string; - wsScheme: string; - apiUrl: string; - wsUrl: string; - authUrl: string; - driveUrl: string; - userAgent: string; - clientEntry: string; -}; - -export type Config = Source & Mixin; diff --git a/packages/backend/src/const.ts b/packages/backend/src/const.ts deleted file mode 100644 index 7e8f96444e..0000000000 --- a/packages/backend/src/const.ts +++ /dev/null @@ -1,71 +0,0 @@ -import config from "@/config/index.js"; -import { DB_MAX_IMAGE_COMMENT_LENGTH } from "@/misc/hard-limits.js"; - -export const MAX_NOTE_TEXT_LENGTH = - config.maxNoteLength != null ? config.maxNoteLength : 3000; // <- should we increase this? -export const MAX_CAPTION_TEXT_LENGTH = Math.min( - config.maxCaptionLength ?? 1500, - DB_MAX_IMAGE_COMMENT_LENGTH, -); - -export const SECOND = 1000; -export const SEC = 1000; // why do we need this duplicate here? -export const MINUTE = 60 * SEC; -export const MIN = 60 * SEC; // why do we need this duplicate here? -export const HOUR = 60 * MIN; -export const DAY = 24 * HOUR; - -export const USER_ONLINE_THRESHOLD = 10 * MINUTE; -export const USER_ACTIVE_THRESHOLD = 3 * DAY; - -// List of file types allowed to be viewed directly in the browser -// Anything not included here will be responded as application/octet-stream -// SVG is not allowed because it generates XSS <- we need to fix this and later allow it to be viewed directly -export const FILE_TYPE_BROWSERSAFE = [ - // Images - "image/png", - "image/gif", // TODO: deprecated, but still used by old notes, new gifs should be converted to webp in the future - "image/jpeg", - "image/webp", // TODO: make this the default image format - "image/apng", - "image/bmp", - "image/tiff", - "image/x-icon", - "image/avif", // not as good supported now, but its good to introduce initial support for the future - - // OggS - "audio/opus", - "video/ogg", - "audio/ogg", - "application/ogg", - - // ISO/IEC base media file format - "video/quicktime", - "video/mp4", // TODO: we need to check for av1 later - "video/vnd.avi", // also av1 - "audio/mp4", - "video/x-m4v", - "audio/x-m4a", - "video/3gpp", - "video/3gpp2", - "video/3gp2", - "audio/3gpp", - "audio/3gpp2", - "audio/3gp2", - - "video/mpeg", - "audio/mpeg", - - "video/webm", - "audio/webm", - - "audio/aac", - "audio/x-flac", - "audio/flac", - "audio/vnd.wave", -]; -/* -https://github.com/sindresorhus/file-type/blob/main/supported.js -https://github.com/sindresorhus/file-type/blob/main/core.js -https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Containers -*/ diff --git a/packages/backend/src/daemons/janitor.ts b/packages/backend/src/daemons/janitor.ts deleted file mode 100644 index 2050d54d4c..0000000000 --- a/packages/backend/src/daemons/janitor.ts +++ /dev/null @@ -1,20 +0,0 @@ -// TODO: 消したい - -const interval = 30 * 60 * 1000; -import { AttestationChallenges } from "@/models/index.js"; -import { LessThan } from "typeorm"; - -/** - * Clean up database occasionally - */ -export default function () { - async function tick() { - await AttestationChallenges.delete({ - createdAt: LessThan(new Date(new Date().getTime() - 5 * 60 * 1000)), - }); - } - - tick(); - - setInterval(tick, interval); -} diff --git a/packages/backend/src/daemons/queue-stats.ts b/packages/backend/src/daemons/queue-stats.ts deleted file mode 100644 index 381b52a916..0000000000 --- a/packages/backend/src/daemons/queue-stats.ts +++ /dev/null @@ -1,60 +0,0 @@ -import Xev from "xev"; -import { deliverQueue, inboxQueue } from "../queue/queues.js"; - -const ev = new Xev(); - -const interval = 10000; - -/** - * Report queue stats regularly - */ -export default function () { - const log = [] as any[]; - - ev.on("requestQueueStatsLog", (x) => { - ev.emit(`queueStatsLog:${x.id}`, log.slice(0, x.length || 50)); - }); - - let activeDeliverJobs = 0; - let activeInboxJobs = 0; - - deliverQueue.on("global:active", () => { - activeDeliverJobs++; - }); - - inboxQueue.on("global:active", () => { - activeInboxJobs++; - }); - - async function tick() { - const deliverJobCounts = await deliverQueue.getJobCounts(); - const inboxJobCounts = await inboxQueue.getJobCounts(); - - const stats = { - deliver: { - activeSincePrevTick: activeDeliverJobs, - active: deliverJobCounts.active, - waiting: deliverJobCounts.waiting, - delayed: deliverJobCounts.delayed, - }, - inbox: { - activeSincePrevTick: activeInboxJobs, - active: inboxJobCounts.active, - waiting: inboxJobCounts.waiting, - delayed: inboxJobCounts.delayed, - }, - }; - - ev.emit("queueStats", stats); - - log.unshift(stats); - if (log.length > 200) log.pop(); - - activeDeliverJobs = 0; - activeInboxJobs = 0; - } - - tick(); - - setInterval(tick, interval); -} diff --git a/packages/backend/src/daemons/server-stats.ts b/packages/backend/src/daemons/server-stats.ts deleted file mode 100644 index b0bf1288fd..0000000000 --- a/packages/backend/src/daemons/server-stats.ts +++ /dev/null @@ -1,79 +0,0 @@ -import si from "systeminformation"; -import Xev from "xev"; -import * as osUtils from "os-utils"; - -const ev = new Xev(); - -const interval = 2000; - -const roundCpu = (num: number) => Math.round(num * 1000) / 1000; -const round = (num: number) => Math.round(num * 10) / 10; - -/** - * Report server stats regularly - */ -export default function () { - const log = [] as any[]; - - ev.on("requestServerStatsLog", (x) => { - ev.emit(`serverStatsLog:${x.id}`, log.slice(0, x.length || 50)); - }); - - async function tick() { - const cpu = await cpuUsage(); - const memStats = await mem(); - const netStats = await net(); - const fsStats = await fs(); - - const stats = { - cpu: roundCpu(cpu), - mem: { - used: round(memStats.used - memStats.buffers - memStats.cached), - active: round(memStats.active), - }, - net: { - rx: round(Math.max(0, netStats.rx_sec)), - tx: round(Math.max(0, netStats.tx_sec)), - }, - fs: { - r: round(Math.max(0, fsStats.rIO_sec ?? 0)), - w: round(Math.max(0, fsStats.wIO_sec ?? 0)), - }, - }; - ev.emit("serverStats", stats); - log.unshift(stats); - if (log.length > 200) log.pop(); - } - - tick(); - - setInterval(tick, interval); -} - -// CPU STAT -function cpuUsage(): Promise<number> { - return new Promise((res, rej) => { - osUtils.cpuUsage((cpuUsage) => { - res(cpuUsage); - }); - }); -} - -// MEMORY STAT -async function mem() { - const data = await si.mem(); - return data; -} - -// NETWORK STAT -async function net() { - const iface = await si.networkInterfaceDefault(); - const data = await si.networkStats(iface); - return data[0]; -} - -// FS STAT -async function fs() { - const data = await si.disksIO().catch(() => ({ rIO_sec: 0, wIO_sec: 0 })); - return data || { rIO_sec: 0, wIO_sec: 0 }; -} diff --git a/packages/backend/src/db/elasticsearch.ts b/packages/backend/src/db/elasticsearch.ts deleted file mode 100644 index 2640e7f918..0000000000 --- a/packages/backend/src/db/elasticsearch.ts +++ /dev/null @@ -1,65 +0,0 @@ -import * as elasticsearch from "@elastic/elasticsearch"; -import config from "@/config/index.js"; - -const index = { - settings: { - analysis: { - analyzer: { - ngram: { - tokenizer: "ngram", - }, - }, - }, - }, - mappings: { - properties: { - text: { - type: "text", - index: true, - analyzer: "ngram", - }, - userId: { - type: "keyword", - index: true, - }, - userHost: { - type: "keyword", - index: true, - }, - }, - }, -}; - -// Init ElasticSearch connection -const client = config.elasticsearch - ? new elasticsearch.Client({ - node: `${config.elasticsearch.ssl ? "https://" : "http://"}${ - config.elasticsearch.host - }:${config.elasticsearch.port}`, - auth: - config.elasticsearch.user && config.elasticsearch.pass - ? { - username: config.elasticsearch.user, - password: config.elasticsearch.pass, - } - : undefined, - pingTimeout: 30000, - }) - : null; - -if (client) { - client.indices - .exists({ - index: config.elasticsearch.index || "misskey_note", - }) - .then((exist) => { - if (!exist.body) { - client.indices.create({ - index: config.elasticsearch.index || "misskey_note", - body: index, - }); - } - }); -} - -export default client; diff --git a/packages/backend/src/db/logger.ts b/packages/backend/src/db/logger.ts deleted file mode 100644 index 28ec65dd24..0000000000 --- a/packages/backend/src/db/logger.ts +++ /dev/null @@ -1,3 +0,0 @@ -import Logger from "@/services/logger.js"; - -export const dbLogger = new Logger("db"); diff --git a/packages/backend/src/db/postgre.ts b/packages/backend/src/db/postgre.ts deleted file mode 100644 index bdeb910e84..0000000000 --- a/packages/backend/src/db/postgre.ts +++ /dev/null @@ -1,262 +0,0 @@ -// https://github.com/typeorm/typeorm/issues/2400 -import pg from "pg"; -pg.types.setTypeParser(20, Number); - -import type { Logger } from "typeorm"; -import { DataSource } from "typeorm"; -import * as highlight from "cli-highlight"; -import config from "@/config/index.js"; - -import { User } from "@/models/entities/user.js"; -import { DriveFile } from "@/models/entities/drive-file.js"; -import { DriveFolder } from "@/models/entities/drive-folder.js"; -import { AccessToken } from "@/models/entities/access-token.js"; -import { App } from "@/models/entities/app.js"; -import { PollVote } from "@/models/entities/poll-vote.js"; -import { Note } from "@/models/entities/note.js"; -import { NoteReaction } from "@/models/entities/note-reaction.js"; -import { NoteWatching } from "@/models/entities/note-watching.js"; -import { NoteThreadMuting } from "@/models/entities/note-thread-muting.js"; -import { NoteUnread } from "@/models/entities/note-unread.js"; -import { Notification } from "@/models/entities/notification.js"; -import { Meta } from "@/models/entities/meta.js"; -import { Following } from "@/models/entities/following.js"; -import { Instance } from "@/models/entities/instance.js"; -import { Muting } from "@/models/entities/muting.js"; -import { RenoteMuting } from "@/models/entities/renote-muting.js"; -import { SwSubscription } from "@/models/entities/sw-subscription.js"; -import { Blocking } from "@/models/entities/blocking.js"; -import { UserList } from "@/models/entities/user-list.js"; -import { UserListJoining } from "@/models/entities/user-list-joining.js"; -import { UserGroup } from "@/models/entities/user-group.js"; -import { UserGroupJoining } from "@/models/entities/user-group-joining.js"; -import { UserGroupInvitation } from "@/models/entities/user-group-invitation.js"; -import { Hashtag } from "@/models/entities/hashtag.js"; -import { NoteFavorite } from "@/models/entities/note-favorite.js"; -import { AbuseUserReport } from "@/models/entities/abuse-user-report.js"; -import { RegistrationTicket } from "@/models/entities/registration-tickets.js"; -import { MessagingMessage } from "@/models/entities/messaging-message.js"; -import { Signin } from "@/models/entities/signin.js"; -import { AuthSession } from "@/models/entities/auth-session.js"; -import { FollowRequest } from "@/models/entities/follow-request.js"; -import { Emoji } from "@/models/entities/emoji.js"; -import { UserNotePining } from "@/models/entities/user-note-pining.js"; -import { Poll } from "@/models/entities/poll.js"; -import { UserKeypair } from "@/models/entities/user-keypair.js"; -import { UserPublickey } from "@/models/entities/user-publickey.js"; -import { UserProfile } from "@/models/entities/user-profile.js"; -import { UserSecurityKey } from "@/models/entities/user-security-key.js"; -import { AttestationChallenge } from "@/models/entities/attestation-challenge.js"; -import { Page } from "@/models/entities/page.js"; -import { PageLike } from "@/models/entities/page-like.js"; -import { GalleryPost } from "@/models/entities/gallery-post.js"; -import { GalleryLike } from "@/models/entities/gallery-like.js"; -import { ModerationLog } from "@/models/entities/moderation-log.js"; -import { UsedUsername } from "@/models/entities/used-username.js"; -import { Announcement } from "@/models/entities/announcement.js"; -import { AnnouncementRead } from "@/models/entities/announcement-read.js"; -import { Clip } from "@/models/entities/clip.js"; -import { ClipNote } from "@/models/entities/clip-note.js"; -import { Antenna } from "@/models/entities/antenna.js"; -import { AntennaNote } from "@/models/entities/antenna-note.js"; -import { PromoNote } from "@/models/entities/promo-note.js"; -import { PromoRead } from "@/models/entities/promo-read.js"; -import { Relay } from "@/models/entities/relay.js"; -import { MutedNote } from "@/models/entities/muted-note.js"; -import { Channel } from "@/models/entities/channel.js"; -import { ChannelFollowing } from "@/models/entities/channel-following.js"; -import { ChannelNotePining } from "@/models/entities/channel-note-pining.js"; -import { RegistryItem } from "@/models/entities/registry-item.js"; -import { Ad } from "@/models/entities/ad.js"; -import { PasswordResetRequest } from "@/models/entities/password-reset-request.js"; -import { UserPending } from "@/models/entities/user-pending.js"; -import { Webhook } from "@/models/entities/webhook.js"; -import { UserIp } from "@/models/entities/user-ip.js"; - -import { entities as charts } from "@/services/chart/entities.js"; -import { envOption } from "../env.js"; -import { dbLogger } from "./logger.js"; -import { redisClient } from "./redis.js"; - -const sqlLogger = dbLogger.createSubLogger("sql", "gray", false); - -class MyCustomLogger implements Logger { - private highlight(sql: string) { - return highlight.highlight(sql, { - language: "sql", - ignoreIllegals: true, - }); - } - - public logQuery(query: string, parameters?: any[]) { - sqlLogger.info(this.highlight(query).substring(0, 100)); - } - - public logQueryError(error: string, query: string, parameters?: any[]) { - sqlLogger.error(this.highlight(query)); - } - - public logQuerySlow(time: number, query: string, parameters?: any[]) { - sqlLogger.warn(this.highlight(query)); - } - - public logSchemaBuild(message: string) { - sqlLogger.info(message); - } - - public log(message: string) { - sqlLogger.info(message); - } - - public logMigration(message: string) { - sqlLogger.info(message); - } -} - -export const entities = [ - Announcement, - AnnouncementRead, - Meta, - Instance, - App, - AuthSession, - AccessToken, - User, - UserProfile, - UserKeypair, - UserPublickey, - UserList, - UserListJoining, - UserGroup, - UserGroupJoining, - UserGroupInvitation, - UserNotePining, - UserSecurityKey, - UsedUsername, - AttestationChallenge, - Following, - FollowRequest, - Muting, - RenoteMuting, - Blocking, - Note, - NoteFavorite, - NoteReaction, - NoteWatching, - NoteThreadMuting, - NoteUnread, - Page, - PageLike, - GalleryPost, - GalleryLike, - DriveFile, - DriveFolder, - Poll, - PollVote, - Notification, - Emoji, - Hashtag, - SwSubscription, - AbuseUserReport, - RegistrationTicket, - MessagingMessage, - Signin, - ModerationLog, - Clip, - ClipNote, - Antenna, - AntennaNote, - PromoNote, - PromoRead, - Relay, - MutedNote, - Channel, - ChannelFollowing, - ChannelNotePining, - RegistryItem, - Ad, - PasswordResetRequest, - UserPending, - Webhook, - UserIp, - ...charts, -]; - -const log = process.env.NODE_ENV !== "production"; - -export const db = new DataSource({ - type: "postgres", - host: config.db.host, - port: config.db.port, - username: config.db.user, - password: config.db.pass, - database: config.db.db, - extra: { - statement_timeout: 1000 * 10, - ...config.db.extra, - }, - synchronize: process.env.NODE_ENV === "test", - dropSchema: process.env.NODE_ENV === "test", - cache: !config.db.disableCache - ? { - type: "ioredis", - options: { - host: config.redis.host, - port: config.redis.port, - family: config.redis.family == null ? 0 : config.redis.family, - password: config.redis.pass, - keyPrefix: `${config.redis.prefix}:query:`, - db: config.redis.db || 0, - }, - } - : false, - logging: log, - logger: log ? new MyCustomLogger() : undefined, - maxQueryExecutionTime: 300, - entities: entities, - migrations: ["../../migration/*.js"], -}); - -export async function initDb(force = false) { - if (force) { - if (db.isInitialized) { - await db.destroy(); - } - await db.initialize(); - return; - } - - if (db.isInitialized) { - // nop - } else { - await db.initialize(); - } -} - -export async function resetDb() { - const reset = async () => { - await redisClient.flushdb(); - const tables = await db.query(`SELECT relname AS "table" - FROM pg_class C LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace) - WHERE nspname NOT IN ('pg_catalog', 'information_schema') - AND C.relkind = 'r' - AND nspname !~ '^pg_toast';`); - for (const table of tables) { - await db.query(`DELETE FROM "${table.table}" CASCADE`); - } - }; - - for (let i = 1; i <= 3; i++) { - try { - await reset(); - } catch (e) { - if (i === 3) { - throw e; - } else { - await new Promise((resolve) => setTimeout(resolve, 1000)); - continue; - } - } - break; - } -} diff --git a/packages/backend/src/db/redis.ts b/packages/backend/src/db/redis.ts deleted file mode 100644 index 6ad3de386f..0000000000 --- a/packages/backend/src/db/redis.ts +++ /dev/null @@ -1,18 +0,0 @@ -import Redis from "ioredis"; -import config from "@/config/index.js"; - -export function createConnection() { - return new Redis({ - port: config.redis.port, - host: config.redis.host, - family: config.redis.family == null ? 0 : config.redis.family, - password: config.redis.pass, - keyPrefix: `${config.redis.prefix}:`, - db: config.redis.db || 0, - }); -} - -export const subscriber = createConnection(); -subscriber.subscribe(config.host); - -export const redisClient = createConnection(); diff --git a/packages/backend/src/db/sonic.ts b/packages/backend/src/db/sonic.ts deleted file mode 100644 index 590c479247..0000000000 --- a/packages/backend/src/db/sonic.ts +++ /dev/null @@ -1,49 +0,0 @@ -import * as SonicChannel from "sonic-channel"; -import { dbLogger } from "./logger.js"; - -import config from "@/config/index.js"; - -const logger = dbLogger.createSubLogger("sonic", "gray", false); - -logger.info("Connecting to Sonic"); - -const handlers = (type: string): SonicChannel.Handlers => ({ - connected: () => { - logger.succ(`Connected to Sonic ${type}`); - }, - disconnected: (error) => { - logger.warn(`Disconnected from Sonic ${type}, error: ${error}`); - }, - error: (error) => { - logger.warn(`Sonic ${type} error: ${error}`); - }, - retrying: () => { - logger.info(`Sonic ${type} retrying`); - }, - timeout: () => { - logger.warn(`Sonic ${type} timeout`); - }, -}); - -const hasConfig = - config.sonic && (config.sonic.host || config.sonic.port || config.sonic.auth); - -const host = hasConfig ? config.sonic.host ?? "localhost" : ""; -const port = hasConfig ? config.sonic.port ?? 1491 : 0; -const auth = hasConfig ? config.sonic.auth ?? "SecretPassword" : ""; -const collection = hasConfig ? config.sonic.collection ?? "main" : ""; -const bucket = hasConfig ? config.sonic.bucket ?? "default" : ""; - -export default hasConfig - ? { - search: new SonicChannel.Search({ host, port, auth }).connect( - handlers("search"), - ), - ingest: new SonicChannel.Ingest({ host, port, auth }).connect( - handlers("ingest"), - ), - - collection, - bucket, - } - : null; diff --git a/packages/backend/src/env.ts b/packages/backend/src/env.ts deleted file mode 100644 index a788a0fba2..0000000000 --- a/packages/backend/src/env.ts +++ /dev/null @@ -1,25 +0,0 @@ -const envOption = { - onlyQueue: false, - onlyServer: false, - noDaemons: false, - disableClustering: false, - verbose: false, - withLogTime: false, - quiet: false, - slow: false, -}; - -for (const key of Object.keys(envOption) as (keyof typeof envOption)[]) { - if ( - process.env[ - `MK_${key.replace(/[A-Z]/g, (letter) => `_${letter}`).toUpperCase()}` - ] - ) - envOption[key] = true; -} - -if (process.env.NODE_ENV === "test") envOption.disableClustering = true; -if (process.env.NODE_ENV === "test") envOption.quiet = true; -if (process.env.NODE_ENV === "test") envOption.noDaemons = true; - -export { envOption }; diff --git a/packages/backend/src/global.d.ts b/packages/backend/src/global.d.ts deleted file mode 100644 index 503e26eb60..0000000000 --- a/packages/backend/src/global.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -// rome-ignore lint/suspicious/noExplicitAny: i have no idea -type FIXME = any; diff --git a/packages/backend/src/index.ts b/packages/backend/src/index.ts deleted file mode 100644 index 278f630f70..0000000000 --- a/packages/backend/src/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * Misskey Entry Point! - */ - -import { EventEmitter } from "node:events"; -import boot from "./boot/index.js"; - -Error.stackTraceLimit = Infinity; -EventEmitter.defaultMaxListeners = 128; - -boot().catch((err) => { - console.error(err); -}); diff --git a/packages/backend/src/main.rs b/packages/backend/src/main.rs new file mode 100644 index 0000000000..336d023394 --- /dev/null +++ b/packages/backend/src/main.rs @@ -0,0 +1,5 @@ + + +fn main() { + +} diff --git a/packages/backend/src/mfm/from-html.ts b/packages/backend/src/mfm/from-html.ts deleted file mode 100644 index 7c956e9058..0000000000 --- a/packages/backend/src/mfm/from-html.ts +++ /dev/null @@ -1,213 +0,0 @@ -import { URL } from "node:url"; -import * as parse5 from "parse5"; -import * as TreeAdapter from "../../node_modules/parse5/dist/tree-adapters/default.js"; - -const treeAdapter = TreeAdapter.defaultTreeAdapter; - -const urlRegex = /^https?:\/\/[\w\/:%#@$&?!()\[\]~.,=+\-]+/; -const urlRegexFull = /^https?:\/\/[\w\/:%#@$&?!()\[\]~.,=+\-]+$/; - -export function fromHtml(html: string, hashtagNames?: string[]): string { - // some AP servers like Pixelfed use br tags as well as newlines - html = html.replace(/<br\s?\/?>\r?\n/gi, "\n"); - - const dom = parse5.parseFragment(html); - - let text = ""; - - for (const n of dom.childNodes) { - analyze(n); - } - - return text.trim(); - - function getText(node: TreeAdapter.Node): string { - if (treeAdapter.isTextNode(node)) return node.value; - if (!treeAdapter.isElementNode(node)) return ""; - if (node.nodeName === "br") return "\n"; - - if (node.childNodes) { - return node.childNodes.map((n) => getText(n)).join(""); - } - - return ""; - } - - function appendChildren(childNodes: TreeAdapter.ChildNode[]): void { - if (childNodes) { - for (const n of childNodes) { - analyze(n); - } - } - } - - function analyze(node: TreeAdapter.Node) { - if (treeAdapter.isTextNode(node)) { - text += node.value; - return; - } - - // Skip comment or document type node - if (!treeAdapter.isElementNode(node)) return; - - switch (node.nodeName) { - case "br": { - text += "\n"; - break; - } - - case "a": { - const txt = getText(node); - const rel = node.attrs.find((x) => x.name === "rel"); - const href = node.attrs.find((x) => x.name === "href"); - - // ハッシュタグ - if ( - hashtagNames && - href && - hashtagNames.map((x) => x.toLowerCase()).includes(txt.toLowerCase()) - ) { - text += txt; - // メンション - } else if (txt.startsWith("@") && !rel?.value.match(/^me /)) { - const part = txt.split("@"); - - if (part.length === 2 && href) { - //#region ホスト名部分が省略されているので復元する - const acct = `${txt}@${new URL(href.value).hostname}`; - text += acct; - //#endregion - } else if (part.length === 3) { - text += txt; - } - // その他 - } else { - const generateLink = () => { - if (!(href || txt)) { - return ""; - } - if (!href) { - return txt; - } - if (!txt || txt === href.value) { - // #6383: Missing text node - if (href.value.match(urlRegexFull)) { - return href.value; - } else { - return `<${href.value}>`; - } - } - if (href.value.match(urlRegex) && !href.value.match(urlRegexFull)) { - return `[${txt}](<${href.value}>)`; // #6846 - } else { - return `[${txt}](${href.value})`; - } - }; - - text += generateLink(); - } - break; - } - - case "h1": { - text += "【"; - appendChildren(node.childNodes); - text += "】\n"; - break; - } - - case "b": - case "strong": { - text += "**"; - appendChildren(node.childNodes); - text += "**"; - break; - } - - case "small": { - text += "<small>"; - appendChildren(node.childNodes); - text += "</small>"; - break; - } - - case "s": - case "del": { - text += "~~"; - appendChildren(node.childNodes); - text += "~~"; - break; - } - - case "i": - case "em": { - text += "<i>"; - appendChildren(node.childNodes); - text += "</i>"; - break; - } - - // block code (<pre><code>) - case "pre": { - if ( - node.childNodes.length === 1 && - node.childNodes[0].nodeName === "code" - ) { - text += "\n```\n"; - text += getText(node.childNodes[0]); - text += "\n```\n"; - } else { - appendChildren(node.childNodes); - } - break; - } - - // inline code (<code>) - case "code": { - text += "`"; - appendChildren(node.childNodes); - text += "`"; - break; - } - - case "blockquote": { - const t = getText(node); - if (t) { - text += "\n> "; - text += t.split("\n").join("\n> "); - } - break; - } - - case "p": - case "h2": - case "h3": - case "h4": - case "h5": - case "h6": { - text += "\n\n"; - appendChildren(node.childNodes); - break; - } - - // other block elements - case "div": - case "header": - case "footer": - case "article": - case "li": - case "dt": - case "dd": { - text += "\n"; - appendChildren(node.childNodes); - break; - } - - default: { - // includes inline elements - appendChildren(node.childNodes); - break; - } - } - } -} diff --git a/packages/backend/src/mfm/to-html.ts b/packages/backend/src/mfm/to-html.ts deleted file mode 100644 index 8d8a4a8889..0000000000 --- a/packages/backend/src/mfm/to-html.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { JSDOM } from "jsdom"; -import type * as mfm from "mfm-js"; -import config from "@/config/index.js"; -import { intersperse } from "@/prelude/array.js"; -import type { IMentionedRemoteUsers } from "@/models/entities/note.js"; - -export function toHtml( - nodes: mfm.MfmNode[] | null, - mentionedRemoteUsers: IMentionedRemoteUsers = [], -) { - if (nodes == null) { - return null; - } - - const { window } = new JSDOM(""); - - const doc = window.document; - - function appendChildren(children: mfm.MfmNode[], targetElement: any): void { - if (children) { - for (const child of children.map((x) => (handlers as any)[x.type](x))) - targetElement.appendChild(child); - } - } - - const handlers: { - [K in mfm.MfmNode["type"]]: (node: mfm.NodeType<K>) => any; - } = { - bold(node) { - const el = doc.createElement("b"); - appendChildren(node.children, el); - return el; - }, - - small(node) { - const el = doc.createElement("small"); - appendChildren(node.children, el); - return el; - }, - - strike(node) { - const el = doc.createElement("del"); - appendChildren(node.children, el); - return el; - }, - - italic(node) { - const el = doc.createElement("i"); - appendChildren(node.children, el); - return el; - }, - - fn(node) { - const el = doc.createElement("i"); - appendChildren(node.children, el); - return el; - }, - - blockCode(node) { - const pre = doc.createElement("pre"); - const inner = doc.createElement("code"); - inner.textContent = node.props.code; - pre.appendChild(inner); - return pre; - }, - - center(node) { - const el = doc.createElement("div"); - appendChildren(node.children, el); - return el; - }, - - emojiCode(node) { - return doc.createTextNode(`\u200B:${node.props.name}:\u200B`); - }, - - unicodeEmoji(node) { - return doc.createTextNode(node.props.emoji); - }, - - hashtag(node) { - const a = doc.createElement("a"); - a.href = `${config.url}/tags/${node.props.hashtag}`; - a.textContent = `#${node.props.hashtag}`; - a.setAttribute("rel", "tag"); - return a; - }, - - inlineCode(node) { - const el = doc.createElement("code"); - el.textContent = node.props.code; - return el; - }, - - mathInline(node) { - const el = doc.createElement("code"); - el.textContent = node.props.formula; - return el; - }, - - mathBlock(node) { - const el = doc.createElement("code"); - el.textContent = node.props.formula; - return el; - }, - - link(node) { - const a = doc.createElement("a"); - a.href = node.props.url; - appendChildren(node.children, a); - return a; - }, - - mention(node) { - const a = doc.createElement("a"); - const { username, host, acct } = node.props; - const remoteUserInfo = mentionedRemoteUsers.find( - (remoteUser) => - remoteUser.username === username && remoteUser.host === host, - ); - a.href = remoteUserInfo - ? remoteUserInfo.url - ? remoteUserInfo.url - : remoteUserInfo.uri - : `${config.url}/${acct}`; - a.className = "u-url mention"; - a.textContent = acct; - return a; - }, - - quote(node) { - const el = doc.createElement("blockquote"); - appendChildren(node.children, el); - return el; - }, - - text(node) { - const el = doc.createElement("span"); - const nodes = node.props.text - .split(/\r\n|\r|\n/) - .map((x) => doc.createTextNode(x)); - - for (const x of intersperse<FIXME | "br">("br", nodes)) { - el.appendChild(x === "br" ? doc.createElement("br") : x); - } - - return el; - }, - - url(node) { - const a = doc.createElement("a"); - a.href = node.props.url; - a.textContent = node.props.url; - return a; - }, - - search(node) { - const a = doc.createElement("a"); - a.href = `https://search.annoyingorange.xyz/search?q=${node.props.query}`; - a.textContent = node.props.content; - return a; - }, - - plain(node) { - const el = doc.createElement("span"); - appendChildren(node.children, el); - return el; - }, - }; - - appendChildren(nodes, doc.body); - - return `<p>${doc.body.innerHTML}</p>`; -} diff --git a/packages/backend/src/misc/acct.ts b/packages/backend/src/misc/acct.ts deleted file mode 100644 index 5b7767a106..0000000000 --- a/packages/backend/src/misc/acct.ts +++ /dev/null @@ -1,14 +0,0 @@ -export type Acct = { - username: string; - host: string | null; -}; - -export function parse(acct: string): Acct { - if (acct.startsWith("@")) acct = acct.substr(1); - const split = acct.split("@", 2); - return { username: split[0], host: split[1] || null }; -} - -export function toString(acct: Acct): string { - return acct.host == null ? acct.username : `${acct.username}@${acct.host}`; -} diff --git a/packages/backend/src/misc/antenna-cache.ts b/packages/backend/src/misc/antenna-cache.ts deleted file mode 100644 index 7f199c3967..0000000000 --- a/packages/backend/src/misc/antenna-cache.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { Antennas } from "@/models/index.js"; -import type { Antenna } from "@/models/entities/antenna.js"; -import { subscriber } from "@/db/redis.js"; - -let antennasFetched = false; -let antennas: Antenna[] = []; - -export async function getAntennas() { - if (!antennasFetched) { - antennas = await Antennas.find(); - antennasFetched = true; - } - - return antennas; -} - -subscriber.on("message", async (_, data) => { - const obj = JSON.parse(data); - - if (obj.channel === "internal") { - const { type, body } = obj.message; - switch (type) { - case "antennaCreated": - antennas.push(body); - break; - case "antennaUpdated": - antennas[antennas.findIndex((a) => a.id === body.id)] = body; - break; - case "antennaDeleted": - antennas = antennas.filter((a) => a.id !== body.id); - break; - default: - break; - } - } -}); diff --git a/packages/backend/src/misc/api-permissions.ts b/packages/backend/src/misc/api-permissions.ts deleted file mode 100644 index 9e040262f1..0000000000 --- a/packages/backend/src/misc/api-permissions.ts +++ /dev/null @@ -1,35 +0,0 @@ -export const kinds = [ - "read:account", - "write:account", - "read:blocks", - "write:blocks", - "read:drive", - "write:drive", - "read:favorites", - "write:favorites", - "read:following", - "write:following", - "read:messaging", - "write:messaging", - "read:mutes", - "write:mutes", - "write:notes", - "read:notifications", - "write:notifications", - "read:reactions", - "write:reactions", - "write:votes", - "read:pages", - "write:pages", - "write:page-likes", - "read:page-likes", - "read:user-groups", - "write:user-groups", - "read:channels", - "write:channels", - "read:gallery", - "write:gallery", - "read:gallery-likes", - "write:gallery-likes", -]; -// IF YOU ADD KINDS(PERMISSIONS), YOU MUST ADD TRANSLATIONS (under _permissions). diff --git a/packages/backend/src/misc/app-lock.ts b/packages/backend/src/misc/app-lock.ts deleted file mode 100644 index 05bcf54244..0000000000 --- a/packages/backend/src/misc/app-lock.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { redisClient } from "../db/redis.js"; -import { promisify } from "node:util"; -import redisLock from "redis-lock"; - -/** - * Retry delay (ms) for lock acquisition - */ -const retryDelay = 100; - -const lock: (key: string, timeout?: number) => Promise<() => void> = redisClient - ? promisify(redisLock(redisClient, retryDelay)) - : async () => () => {}; - -/** - * Get AP Object lock - * @param uri AP object ID - * @param timeout Lock timeout (ms), The timeout releases previous lock. - * @returns Unlock function - */ -export function getApLock(uri: string, timeout = 30 * 1000) { - return lock(`ap-object:${uri}`, timeout); -} - -export function getFetchInstanceMetadataLock( - host: string, - timeout = 30 * 1000, -) { - return lock(`instance:${host}`, timeout); -} - -export function getChartInsertLock(lockKey: string, timeout = 30 * 1000) { - return lock(`chart-insert:${lockKey}`, timeout); -} diff --git a/packages/backend/src/misc/before-shutdown.ts b/packages/backend/src/misc/before-shutdown.ts deleted file mode 100644 index 0820418356..0000000000 --- a/packages/backend/src/misc/before-shutdown.ts +++ /dev/null @@ -1,103 +0,0 @@ -// https://gist.github.com/nfantone/1eaa803772025df69d07f4dbf5df7e58 - -"use strict"; - -/** - * @callback BeforeShutdownListener - * @param {string} [signalOrEvent] The exit signal or event name received on the process. - */ - -/** - * System signals the app will listen to initiate shutdown. - * @const {string[]} - */ -const SHUTDOWN_SIGNALS = ["SIGINT", "SIGTERM"]; - -/** - * Time in milliseconds to wait before forcing shutdown. - * @const {number} - */ -const SHUTDOWN_TIMEOUT = 15000; - -/** - * A queue of listener callbacks to execute before shutting - * down the process. - * @type {BeforeShutdownListener[]} - */ -const shutdownListeners: ((signalOrEvent: string) => void)[] = []; - -/** - * Listen for signals and execute given `fn` function once. - * @param {string[]} signals System signals to listen to. - * @param {function(string)} fn Function to execute on shutdown. - */ -const processOnce = ( - signals: string[], - fn: (signalOrEvent: string) => void, -) => { - for (const sig of signals) { - process.once(sig, fn); - } -}; - -/** - * Sets a forced shutdown mechanism that will exit the process after `timeout` milliseconds. - * @param {number} timeout Time to wait before forcing shutdown (milliseconds) - */ -const forceExitAfter = (timeout: number) => () => { - setTimeout(() => { - // Force shutdown after timeout - console.warn( - `Could not close resources gracefully after ${timeout}ms: forcing shutdown`, - ); - return process.exit(1); - }, timeout).unref(); -}; - -/** - * Main process shutdown handler. Will invoke every previously registered async shutdown listener - * in the queue and exit with a code of `0`. Any `Promise` rejections from any listener will - * be logged out as a warning, but won't prevent other callbacks from executing. - * @param {string} signalOrEvent The exit signal or event name received on the process. - */ -async function shutdownHandler(signalOrEvent: string) { - if (process.env.NODE_ENV === "test") return process.exit(0); - - console.warn(`Shutting down: received [${signalOrEvent}] signal`); - - for (const listener of shutdownListeners) { - try { - await listener(signalOrEvent); - } catch (err) { - if (err instanceof Error) { - console.warn( - `A shutdown handler failed before completing with: ${ - err.message || err - }`, - ); - } - } - } - - return process.exit(0); -} - -/** - * Registers a new shutdown listener to be invoked before exiting - * the main process. Listener handlers are guaranteed to be called in the order - * they were registered. - * @param {BeforeShutdownListener} listener The shutdown listener to register. - * @returns {BeforeShutdownListener} Echoes back the supplied `listener`. - */ -export function beforeShutdown(listener: () => void) { - shutdownListeners.push(listener); - return listener; -} - -// Register shutdown callback that kills the process after `SHUTDOWN_TIMEOUT` milliseconds -// This prevents custom shutdown handlers from hanging the process indefinitely -processOnce(SHUTDOWN_SIGNALS, forceExitAfter(SHUTDOWN_TIMEOUT)); - -// Register process shutdown callback -// Will listen to incoming signal events and execute all registered handlers in the stack -processOnce(SHUTDOWN_SIGNALS, shutdownHandler); diff --git a/packages/backend/src/misc/cache.ts b/packages/backend/src/misc/cache.ts deleted file mode 100644 index 9abebc91cb..0000000000 --- a/packages/backend/src/misc/cache.ts +++ /dev/null @@ -1,88 +0,0 @@ -export class Cache<T> { - public cache: Map<string | null, { date: number; value: T }>; - private lifetime: number; - - constructor(lifetime: Cache<never>["lifetime"]) { - this.cache = new Map(); - this.lifetime = lifetime; - } - - public set(key: string | null, value: T): void { - this.cache.set(key, { - date: Date.now(), - value, - }); - } - - public get(key: string | null): T | undefined { - const cached = this.cache.get(key); - if (cached == null) return undefined; - if (Date.now() - cached.date > this.lifetime) { - this.cache.delete(key); - return undefined; - } - return cached.value; - } - - public delete(key: string | null) { - this.cache.delete(key); - } - - /** - * キャッシュがあればそれを返し、無ければfetcherを呼び出して結果をキャッシュ&返します - * optional: キャッシュが存在してもvalidatorでfalseを返すとキャッシュ無効扱いにします - */ - public async fetch( - key: string | null, - fetcher: () => Promise<T>, - validator?: (cachedValue: T) => boolean, - ): Promise<T> { - const cachedValue = this.get(key); - if (cachedValue !== undefined) { - if (validator) { - if (validator(cachedValue)) { - // Cache HIT - return cachedValue; - } - } else { - // Cache HIT - return cachedValue; - } - } - - // Cache MISS - const value = await fetcher(); - this.set(key, value); - return value; - } - - /** - * キャッシュがあればそれを返し、無ければfetcherを呼び出して結果をキャッシュ&返します - * optional: キャッシュが存在してもvalidatorでfalseを返すとキャッシュ無効扱いにします - */ - public async fetchMaybe( - key: string | null, - fetcher: () => Promise<T | undefined>, - validator?: (cachedValue: T) => boolean, - ): Promise<T | undefined> { - const cachedValue = this.get(key); - if (cachedValue !== undefined) { - if (validator) { - if (validator(cachedValue)) { - // Cache HIT - return cachedValue; - } - } else { - // Cache HIT - return cachedValue; - } - } - - // Cache MISS - const value = await fetcher(); - if (value !== undefined) { - this.set(key, value); - } - return value; - } -} diff --git a/packages/backend/src/misc/captcha.ts b/packages/backend/src/misc/captcha.ts deleted file mode 100644 index 8ea4abedb6..0000000000 --- a/packages/backend/src/misc/captcha.ts +++ /dev/null @@ -1,73 +0,0 @@ -import fetch from "node-fetch"; -import { URLSearchParams } from "node:url"; -import { getAgentByUrl } from "./fetch.js"; -import config from "@/config/index.js"; - -export async function verifyRecaptcha(secret: string, response: string) { - const result = await getCaptchaResponse( - "https://www.recaptcha.net/recaptcha/api/siteverify", - secret, - response, - ).catch((e) => { - throw new Error(`recaptcha-request-failed: ${e.message}`); - }); - - if (result.success !== true) { - const errorCodes = result["error-codes"] - ? result["error-codes"]?.join(", ") - : ""; - throw new Error(`recaptcha-failed: ${errorCodes}`); - } -} - -export async function verifyHcaptcha(secret: string, response: string) { - const result = await getCaptchaResponse( - "https://hcaptcha.com/siteverify", - secret, - response, - ).catch((e) => { - throw new Error(`hcaptcha-request-failed: ${e.message}`); - }); - - if (result.success !== true) { - const errorCodes = result["error-codes"] - ? result["error-codes"]?.join(", ") - : ""; - throw new Error(`hcaptcha-failed: ${errorCodes}`); - } -} - -type CaptchaResponse = { - success: boolean; - "error-codes"?: string[]; -}; - -async function getCaptchaResponse( - url: string, - secret: string, - response: string, -): Promise<CaptchaResponse> { - const params = new URLSearchParams({ - secret, - response, - }); - - const res = await fetch(url, { - method: "POST", - body: params, - headers: { - "User-Agent": config.userAgent, - }, - // TODO - //timeout: 10 * 1000, - agent: getAgentByUrl, - }).catch((e) => { - throw new Error(`${e.message || e}`); - }); - - if (!res.ok) { - throw new Error(`${res.status}`); - } - - return (await res.json()) as CaptchaResponse; -} diff --git a/packages/backend/src/misc/check-hit-antenna.ts b/packages/backend/src/misc/check-hit-antenna.ts deleted file mode 100644 index adcdd190f8..0000000000 --- a/packages/backend/src/misc/check-hit-antenna.ts +++ /dev/null @@ -1,137 +0,0 @@ -import type { Antenna } from "@/models/entities/antenna.js"; -import type { Note } from "@/models/entities/note.js"; -import type { User } from "@/models/entities/user.js"; -import { - UserListJoinings, - UserGroupJoinings, - Blockings, -} from "@/models/index.js"; -import { getFullApAccount } from "./convert-host.js"; -import * as Acct from "@/misc/acct.js"; -import type { Packed } from "./schema.js"; -import { Cache } from "./cache.js"; - -const blockingCache = new Cache<User["id"][]>(1000 * 60 * 5); - -// NOTE: フォローしているユーザーのノート、リストのユーザーのノート、グループのユーザーのノート指定はパフォーマンス上の理由で無効になっている - -/** - * noteUserFollowers / antennaUserFollowing はどちらか一方が指定されていればよい - */ -export async function checkHitAntenna( - antenna: Antenna, - note: Note | Packed<"Note">, - noteUser: { id: User["id"]; username: string; host: string | null }, - noteUserFollowers?: User["id"][], - antennaUserFollowing?: User["id"][], -): Promise<boolean> { - if (note.visibility === "specified") return false; - - // アンテナ作成者がノート作成者にブロックされていたらスキップ - const blockings = await blockingCache.fetch(noteUser.id, () => - Blockings.findBy({ blockerId: noteUser.id }).then((res) => - res.map((x) => x.blockeeId), - ), - ); - if (blockings.some((blocking) => blocking === antenna.userId)) return false; - - if (note.visibility === "followers") { - if (noteUserFollowers && !noteUserFollowers.includes(antenna.userId)) - return false; - if (antennaUserFollowing && !antennaUserFollowing.includes(note.userId)) - return false; - } - - if (!antenna.withReplies && note.replyId != null) return false; - - if (antenna.src === "home") { - if (noteUserFollowers && !noteUserFollowers.includes(antenna.userId)) - return false; - if (antennaUserFollowing && !antennaUserFollowing.includes(note.userId)) - return false; - } else if (antenna.src === "list") { - const listUsers = ( - await UserListJoinings.findBy({ - userListId: antenna.userListId!, - }) - ).map((x) => x.userId); - - if (!listUsers.includes(note.userId)) return false; - } else if (antenna.src === "group") { - const joining = await UserGroupJoinings.findOneByOrFail({ - id: antenna.userGroupJoiningId!, - }); - - const groupUsers = ( - await UserGroupJoinings.findBy({ - userGroupId: joining.userGroupId, - }) - ).map((x) => x.userId); - - if (!groupUsers.includes(note.userId)) return false; - } else if (antenna.src === "users") { - const accts = antenna.users.map((x) => { - const { username, host } = Acct.parse(x); - return getFullApAccount(username, host).toLowerCase(); - }); - if ( - !accts.includes( - getFullApAccount(noteUser.username, noteUser.host).toLowerCase(), - ) - ) - return false; - } else if (antenna.src === "instances") { - const instances = antenna.instances - .filter((x) => x !== "") - .map((host) => { - return host.toLowerCase(); - }); - if (!instances.includes(noteUser.host?.toLowerCase() ?? "")) return false; - } - - const keywords = antenna.keywords - // Clean up - .map((xs) => xs.filter((x) => x !== "")) - .filter((xs) => xs.length > 0); - - if (keywords.length > 0) { - if (note.text == null) return false; - - const matched = keywords.some((and) => - and.every((keyword) => - antenna.caseSensitive - ? note.text!.includes(keyword) - : note.text!.toLowerCase().includes(keyword.toLowerCase()), - ), - ); - - if (!matched) return false; - } - - const excludeKeywords = antenna.excludeKeywords - // Clean up - .map((xs) => xs.filter((x) => x !== "")) - .filter((xs) => xs.length > 0); - - if (excludeKeywords.length > 0) { - if (note.text == null) return false; - - const matched = excludeKeywords.some((and) => - and.every((keyword) => - antenna.caseSensitive - ? note.text!.includes(keyword) - : note.text!.toLowerCase().includes(keyword.toLowerCase()), - ), - ); - - if (matched) return false; - } - - if (antenna.withFile) { - if (note.fileIds && note.fileIds.length === 0) return false; - } - - // TODO: eval expression - - return true; -} diff --git a/packages/backend/src/misc/check-word-mute.ts b/packages/backend/src/misc/check-word-mute.ts deleted file mode 100644 index 53193d851a..0000000000 --- a/packages/backend/src/misc/check-word-mute.ts +++ /dev/null @@ -1,78 +0,0 @@ -import RE2 from "re2"; -import type { Note } from "@/models/entities/note.js"; -import type { User } from "@/models/entities/user.js"; - -type NoteLike = { - userId: Note["userId"]; - text: Note["text"]; - cw?: Note["cw"]; -}; - -type UserLike = { - id: User["id"]; -}; - -export type Muted = { - muted: boolean; - matched: string[]; -}; - -const NotMuted = { muted: false, matched: [] }; - -function escapeRegExp(x: string) { - return x.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string -} - -export async function getWordMute( - note: NoteLike, - me: UserLike | null | undefined, - mutedWords: Array<string | string[]>, -): Promise<Muted> { - // 自分自身 - if (me && note.userId === me.id) { - return NotMuted; - } - - if (mutedWords.length > 0) { - const text = ((note.cw ?? "") + "\n" + (note.text ?? "")).trim(); - - if (text === "") { - return NotMuted; - } - - for (const mutePattern of mutedWords) { - let mute: RE2; - let matched: string[]; - if (Array.isArray(mutePattern)) { - matched = mutePattern.filter((keyword) => keyword !== ""); - - if (matched.length === 0) { - continue; - } - mute = new RE2( - `\\b${matched.map(escapeRegExp).join("\\b.*\\b")}\\b`, - "g", - ); - } else { - const regexp = mutePattern.match(/^\/(.+)\/(.*)$/); - // This should never happen due to input sanitisation. - if (!regexp) { - console.warn(`Found invalid regex in word mutes: ${mutePattern}`); - continue; - } - mute = new RE2(regexp[1], regexp[2]); - matched = [mutePattern]; - } - - try { - if (mute.test(text)) { - return { muted: true, matched }; - } - } catch (err) { - // This should never happen due to input sanitisation. - } - } - } - - return NotMuted; -} diff --git a/packages/backend/src/misc/clone.ts b/packages/backend/src/misc/clone.ts deleted file mode 100644 index 4322e2e28f..0000000000 --- a/packages/backend/src/misc/clone.ts +++ /dev/null @@ -1,24 +0,0 @@ -// structredCloneが遅いため -// SEE: http://var.blog.jp/archives/86038606.html - -type Cloneable = - | string - | number - | boolean - | null - | { [key: string]: Cloneable } - | Cloneable[]; - -export function deepClone<T extends Cloneable>(x: T): T { - if (typeof x === "object") { - if (x === null) return x; - if (Array.isArray(x)) return x.map(deepClone) as T; - const obj = {} as Record<string, Cloneable>; - for (const [k, v] of Object.entries(x)) { - obj[k] = deepClone(v); - } - return obj as T; - } else { - return x; - } -} diff --git a/packages/backend/src/misc/content-disposition.ts b/packages/backend/src/misc/content-disposition.ts deleted file mode 100644 index 25d6f58177..0000000000 --- a/packages/backend/src/misc/content-disposition.ts +++ /dev/null @@ -1,9 +0,0 @@ -import cd from "content-disposition"; - -export function contentDisposition( - type: "inline" | "attachment", - filename: string, -): string { - const fallback = filename.replace(/[^\w.-]/g, "_"); - return cd(filename, { type, fallback }); -} diff --git a/packages/backend/src/misc/convert-host.ts b/packages/backend/src/misc/convert-host.ts deleted file mode 100644 index 856ce3c127..0000000000 --- a/packages/backend/src/misc/convert-host.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { URL } from "node:url"; -import config from "@/config/index.js"; -import { toASCII } from "punycode"; - -export function getFullApAccount(username: string, host: string | null) { - return host - ? `${username}@${toPuny(host)}` - : `${username}@${toPuny(config.host)}`; -} - -export function isSelfHost(host: string) { - if (host == null) return true; - return toPuny(config.host) === toPuny(host); -} - -export function extractDbHost(uri: string) { - const url = new URL(uri); - return toPuny(url.hostname); -} - -export function toPuny(host: string) { - return toASCII(host.toLowerCase()); -} - -export function toPunyNullable(host: string | null | undefined): string | null { - if (host == null) return null; - return toASCII(host.toLowerCase()); -} diff --git a/packages/backend/src/misc/count-same-renotes.ts b/packages/backend/src/misc/count-same-renotes.ts deleted file mode 100644 index 45a6c1d35a..0000000000 --- a/packages/backend/src/misc/count-same-renotes.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { Notes } from "@/models/index.js"; - -export async function countSameRenotes( - userId: string, - renoteId: string, - excludeNoteId: string | undefined, -): Promise<number> { - // 指定したユーザーの指定したノートのリノートがいくつあるか数える - const query = Notes.createQueryBuilder("note") - .where("note.userId = :userId", { userId }) - .andWhere("note.renoteId = :renoteId", { renoteId }); - - // 指定した投稿を除く - if (excludeNoteId) { - query.andWhere("note.id != :excludeNoteId", { excludeNoteId }); - } - - return await query.getCount(); -} diff --git a/packages/backend/src/misc/create-temp.ts b/packages/backend/src/misc/create-temp.ts deleted file mode 100644 index 16c85ee7bd..0000000000 --- a/packages/backend/src/misc/create-temp.ts +++ /dev/null @@ -1,24 +0,0 @@ -import * as tmp from "tmp"; - -export function createTemp(): Promise<[string, () => void]> { - return new Promise<[string, () => void]>((res, rej) => { - tmp.file((e, path, fd, cleanup) => { - if (e) return rej(e); - res([path, cleanup]); - }); - }); -} - -export function createTempDir(): Promise<[string, () => void]> { - return new Promise<[string, () => void]>((res, rej) => { - tmp.dir( - { - unsafeCleanup: true, - }, - (e, path, cleanup) => { - if (e) return rej(e); - res([path, cleanup]); - }, - ); - }); -} diff --git a/packages/backend/src/misc/detect-url-mime.ts b/packages/backend/src/misc/detect-url-mime.ts deleted file mode 100644 index 9f0e4325d9..0000000000 --- a/packages/backend/src/misc/detect-url-mime.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { createTemp } from "./create-temp.js"; -import { downloadUrl } from "./download-url.js"; -import { detectType } from "./get-file-info.js"; - -export async function detectUrlMime(url: string) { - const [path, cleanup] = await createTemp(); - - try { - await downloadUrl(url, path); - const { mime } = await detectType(path); - return mime; - } finally { - cleanup(); - } -} diff --git a/packages/backend/src/misc/download-text-file.ts b/packages/backend/src/misc/download-text-file.ts deleted file mode 100644 index 9d3821b20f..0000000000 --- a/packages/backend/src/misc/download-text-file.ts +++ /dev/null @@ -1,25 +0,0 @@ -import * as fs from "node:fs"; -import * as util from "node:util"; -import Logger from "@/services/logger.js"; -import { createTemp } from "./create-temp.js"; -import { downloadUrl } from "./download-url.js"; - -const logger = new Logger("download-text-file"); - -export async function downloadTextFile(url: string): Promise<string> { - // Create temp file - const [path, cleanup] = await createTemp(); - - logger.info(`Temp file is ${path}`); - - try { - // write content at URL to temp file - await downloadUrl(url, path); - - const text = await util.promisify(fs.readFile)(path, "utf8"); - - return text; - } finally { - cleanup(); - } -} diff --git a/packages/backend/src/misc/download-url.ts b/packages/backend/src/misc/download-url.ts deleted file mode 100644 index 7fafb635ba..0000000000 --- a/packages/backend/src/misc/download-url.ts +++ /dev/null @@ -1,103 +0,0 @@ -import * as fs from "node:fs"; -import * as stream from "node:stream"; -import * as util from "node:util"; -import got, * as Got from "got"; -import { httpAgent, httpsAgent, StatusError } from "./fetch.js"; -import config from "@/config/index.js"; -import chalk from "chalk"; -import Logger from "@/services/logger.js"; -import IPCIDR from "ip-cidr"; -import PrivateIp from "private-ip"; - -const pipeline = util.promisify(stream.pipeline); - -export async function downloadUrl(url: string, path: string): Promise<void> { - const logger = new Logger("download"); - - logger.info(`Downloading ${chalk.cyan(url)} ...`); - - const timeout = 30 * 1000; - const operationTimeout = 60 * 1000; - const maxSize = config.maxFileSize || 262144000; - - const req = got - .stream(url, { - headers: { - "User-Agent": config.userAgent, - }, - timeout: { - lookup: timeout, - connect: timeout, - secureConnect: timeout, - socket: timeout, // read timeout - response: timeout, - send: timeout, - request: operationTimeout, // whole operation timeout - }, - agent: { - http: httpAgent, - https: httpsAgent, - }, - http2: false, // default - retry: { - limit: 0, - }, - }) - .on("response", (res: Got.Response) => { - if ( - (process.env.NODE_ENV === "production" || - process.env.NODE_ENV === "test") && - !config.proxy && - res.ip - ) { - if (isPrivateIp(res.ip)) { - logger.warn(`Blocked address: ${res.ip}`); - req.destroy(); - } - } - - const contentLength = res.headers["content-length"]; - if (contentLength != null) { - const size = Number(contentLength); - if (size > maxSize) { - logger.warn(`maxSize exceeded (${size} > ${maxSize}) on response`); - req.destroy(); - } - } - }) - .on("downloadProgress", (progress: Got.Progress) => { - if (progress.transferred > maxSize) { - logger.warn( - `maxSize exceeded (${progress.transferred} > ${maxSize}) on downloadProgress`, - ); - req.destroy(); - } - }); - - try { - await pipeline(req, fs.createWriteStream(path)); - } catch (e) { - if (e instanceof Got.HTTPError) { - throw new StatusError( - `${e.response.statusCode} ${e.response.statusMessage}`, - e.response.statusCode, - e.response.statusMessage, - ); - } else { - throw e; - } - } - - logger.succ(`Download finished: ${chalk.cyan(url)}`); -} - -function isPrivateIp(ip: string): boolean { - for (const net of config.allowedPrivateNetworks || []) { - const cidr = new IPCIDR(net); - if (cidr.contains(ip)) { - return false; - } - } - - return PrivateIp(ip); -} diff --git a/packages/backend/src/misc/emoji-regex.ts b/packages/backend/src/misc/emoji-regex.ts deleted file mode 100644 index 08b44788de..0000000000 --- a/packages/backend/src/misc/emoji-regex.ts +++ /dev/null @@ -1,5 +0,0 @@ -import twemoji from "twemoji-parser/dist/lib/regex.js"; -const twemojiRegex = twemoji.default; - -export const emojiRegex = new RegExp(`(${twemojiRegex.source})`); -export const emojiRegexAtStartToEnd = new RegExp(`^(${twemojiRegex.source})$`); diff --git a/packages/backend/src/misc/extract-custom-emojis-from-mfm.ts b/packages/backend/src/misc/extract-custom-emojis-from-mfm.ts deleted file mode 100644 index 7de32e6d60..0000000000 --- a/packages/backend/src/misc/extract-custom-emojis-from-mfm.ts +++ /dev/null @@ -1,10 +0,0 @@ -import * as mfm from "mfm-js"; -import { unique } from "@/prelude/array.js"; - -export function extractCustomEmojisFromMfm(nodes: mfm.MfmNode[]): string[] { - const emojiNodes = mfm.extract(nodes, (node) => { - return node.type === "emojiCode" && node.props.name.length <= 100; - }); - - return unique(emojiNodes.map((x) => x.props.name)); -} diff --git a/packages/backend/src/misc/extract-hashtags.ts b/packages/backend/src/misc/extract-hashtags.ts deleted file mode 100644 index 826e36221b..0000000000 --- a/packages/backend/src/misc/extract-hashtags.ts +++ /dev/null @@ -1,9 +0,0 @@ -import * as mfm from "mfm-js"; -import { unique } from "@/prelude/array.js"; - -export function extractHashtags(nodes: mfm.MfmNode[]): string[] { - const hashtagNodes = mfm.extract(nodes, (node) => node.type === "hashtag"); - const hashtags = unique(hashtagNodes.map((x) => x.props.hashtag)); - - return hashtags; -} diff --git a/packages/backend/src/misc/extract-mentions.ts b/packages/backend/src/misc/extract-mentions.ts deleted file mode 100644 index 259f78e576..0000000000 --- a/packages/backend/src/misc/extract-mentions.ts +++ /dev/null @@ -1,13 +0,0 @@ -// test is located in test/extract-mentions - -import * as mfm from "mfm-js"; - -export function extractMentions( - nodes: mfm.MfmNode[], -): mfm.MfmMention["props"][] { - // TODO: 重複を削除 - const mentionNodes = mfm.extract(nodes, (node) => node.type === "mention"); - const mentions = mentionNodes.map((x) => x.props); - - return mentions; -} diff --git a/packages/backend/src/misc/fetch-meta.ts b/packages/backend/src/misc/fetch-meta.ts deleted file mode 100644 index 32c45813ca..0000000000 --- a/packages/backend/src/misc/fetch-meta.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { Meta } from "@/models/entities/meta.js"; - -let cache: Meta; - -export async function fetchMeta(noCache = false): Promise<Meta> { - if (!noCache && cache) return cache; - - return await db.transaction(async (transactionalEntityManager) => { - // New IDs are prioritized because multiple records may have been created due to past bugs. - const metas = await transactionalEntityManager.find(Meta, { - order: { - id: "DESC", - }, - }); - - const meta = metas[0]; - - if (meta) { - cache = meta; - return meta; - } else { - // If fetchMeta is called at the same time when meta is empty, this part may be called at the same time, so use fail-safe upsert. - const saved = await transactionalEntityManager - .upsert( - Meta, - { - id: "x", - }, - ["id"], - ) - .then((x) => - transactionalEntityManager.findOneByOrFail(Meta, x.identifiers[0]), - ); - - cache = saved; - return saved; - } - }); -} - -setInterval(() => { - fetchMeta(true).then((meta) => { - cache = meta; - }); -}, 1000 * 10); diff --git a/packages/backend/src/misc/fetch-proxy-account.ts b/packages/backend/src/misc/fetch-proxy-account.ts deleted file mode 100644 index a277db6fb9..0000000000 --- a/packages/backend/src/misc/fetch-proxy-account.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { fetchMeta } from "./fetch-meta.js"; -import type { ILocalUser } from "@/models/entities/user.js"; -import { Users } from "@/models/index.js"; - -export async function fetchProxyAccount(): Promise<ILocalUser | null> { - const meta = await fetchMeta(); - if (meta.proxyAccountId == null) return null; - return (await Users.findOneByOrFail({ - id: meta.proxyAccountId, - })) as ILocalUser; -} diff --git a/packages/backend/src/misc/fetch.ts b/packages/backend/src/misc/fetch.ts deleted file mode 100644 index 0e673ba3a8..0000000000 --- a/packages/backend/src/misc/fetch.ts +++ /dev/null @@ -1,171 +0,0 @@ -import * as http from "node:http"; -import * as https from "node:https"; -import type { URL } from "node:url"; -import CacheableLookup from "cacheable-lookup"; -import fetch from "node-fetch"; -import { HttpProxyAgent, HttpsProxyAgent } from "hpagent"; -import config from "@/config/index.js"; - -export async function getJson( - url: string, - accept = "application/json, */*", - timeout = 10000, - headers?: Record<string, string>, -) { - const res = await getResponse({ - url, - method: "GET", - headers: Object.assign( - { - "User-Agent": config.userAgent, - Accept: accept, - }, - headers || {}, - ), - timeout, - }); - - return await res.json(); -} - -export async function getHtml( - url: string, - accept = "text/html, */*", - timeout = 10000, - headers?: Record<string, string>, -) { - const res = await getResponse({ - url, - method: "GET", - headers: Object.assign( - { - "User-Agent": config.userAgent, - Accept: accept, - }, - headers || {}, - ), - timeout, - }); - - return await res.text(); -} - -export async function getResponse(args: { - url: string; - method: string; - body?: string; - headers: Record<string, string>; - timeout?: number; - size?: number; -}) { - const timeout = args.timeout || 10 * 1000; - - const controller = new AbortController(); - setTimeout(() => { - controller.abort(); - }, timeout * 6); - - const res = await fetch(args.url, { - method: args.method, - headers: args.headers, - body: args.body, - timeout, - size: args.size || 10 * 1024 * 1024, - agent: getAgentByUrl, - signal: controller.signal, - }); - - if (!res.ok) { - throw new StatusError( - `${res.status} ${res.statusText}`, - res.status, - res.statusText, - ); - } - - return res; -} - -const cache = new CacheableLookup({ - maxTtl: 3600, // 1hours - errorTtl: 30, // 30secs - lookup: false, // nativeのdns.lookupにfallbackしない -}); - -/** - * Get http non-proxy agent - */ -const _http = new http.Agent({ - keepAlive: true, - keepAliveMsecs: 30 * 1000, - lookup: cache.lookup, -} as http.AgentOptions); - -/** - * Get https non-proxy agent - */ -const _https = new https.Agent({ - keepAlive: true, - keepAliveMsecs: 30 * 1000, - lookup: cache.lookup, -} as https.AgentOptions); - -const maxSockets = Math.max(256, config.deliverJobConcurrency || 128); - -/** - * Get http proxy or non-proxy agent - */ -export const httpAgent = config.proxy - ? new HttpProxyAgent({ - keepAlive: true, - keepAliveMsecs: 30 * 1000, - maxSockets, - maxFreeSockets: 256, - scheduling: "lifo", - proxy: config.proxy, - }) - : _http; - -/** - * Get https proxy or non-proxy agent - */ -export const httpsAgent = config.proxy - ? new HttpsProxyAgent({ - keepAlive: true, - keepAliveMsecs: 30 * 1000, - maxSockets, - maxFreeSockets: 256, - scheduling: "lifo", - proxy: config.proxy, - }) - : _https; - -/** - * Get agent by URL - * @param url URL - * @param bypassProxy Allways bypass proxy - */ -export function getAgentByUrl(url: URL, bypassProxy = false) { - if (bypassProxy || (config.proxyBypassHosts || []).includes(url.hostname)) { - return url.protocol === "http:" ? _http : _https; - } else { - return url.protocol === "http:" ? httpAgent : httpsAgent; - } -} - -export class StatusError extends Error { - public statusCode: number; - public statusMessage?: string; - public isClientError: boolean; - - constructor(message: string, statusCode: number, statusMessage?: string) { - super(message); - this.name = "StatusError"; - this.statusCode = statusCode; - this.statusMessage = statusMessage; - this.isClientError = - typeof this.statusCode === "number" && - this.statusCode >= 400 && - this.statusCode < 500; - } -} diff --git a/packages/backend/src/misc/gen-id.ts b/packages/backend/src/misc/gen-id.ts deleted file mode 100644 index b7cc0965a1..0000000000 --- a/packages/backend/src/misc/gen-id.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { ulid } from "ulid"; -import { genAid } from "./id/aid.js"; -import { genMeid } from "./id/meid.js"; -import { genMeidg } from "./id/meidg.js"; -import { genObjectId } from "./id/object-id.js"; -import config from "@/config/index.js"; - -const metohd = config.id.toLowerCase(); - -export function genId(date?: Date): string { - if (!date || date > new Date()) date = new Date(); - - switch (metohd) { - case "aid": - return genAid(date); - case "meid": - return genMeid(date); - case "meidg": - return genMeidg(date); - case "ulid": - return ulid(date.getTime()); - case "objectid": - return genObjectId(date); - default: - throw new Error("unrecognized id generation method"); - } -} diff --git a/packages/backend/src/misc/gen-identicon.ts b/packages/backend/src/misc/gen-identicon.ts deleted file mode 100644 index 1e51dfe2ac..0000000000 --- a/packages/backend/src/misc/gen-identicon.ts +++ /dev/null @@ -1,114 +0,0 @@ -/** - * Identicon generator - * https://en.wikipedia.org/wiki/Identicon - */ - -import type { WriteStream } from "node:fs"; -import * as p from "pureimage"; -import gen from "random-seed"; - -const size = 128; // px -const n = 5; // resolution -const margin = size / 4; -const colors = [ - ["#eb6f92", "#b4637a"], - ["#f6c177", "#ea9d34"], - ["#ebbcba", "#d7827e"], - ["#9ccfd8", "#56949f"], - ["#c4a7e7", "#907aa9"], - ["#eb6f92", "#f6c177"], - ["#eb6f92", "#ebbcba"], - ["#eb6f92", "#31748f"], - ["#eb6f92", "#9ccfd8"], - ["#eb6f92", "#c4a7e7"], - ["#f6c177", "#eb6f92"], - ["#f6c177", "#ebbcba"], - ["#f6c177", "#31748f"], - ["#f6c177", "#9ccfd8"], - ["#f6c177", "#c4a7e7"], - ["#ebbcba", "#eb6f92"], - ["#ebbcba", "#f6c177"], - ["#ebbcba", "#31748f"], - ["#ebbcba", "#9ccfd8"], - ["#ebbcba", "#c4a7e7"], - ["#31748f", "#eb6f92"], - ["#31748f", "#f6c177"], - ["#31748f", "#ebbcba"], - ["#31748f", "#9ccfd8"], - ["#31748f", "#c4a7e7"], - ["#9ccfd8", "#eb6f92"], - ["#9ccfd8", "#f6c177"], - ["#9ccfd8", "#ebbcba"], - ["#9ccfd8", "#31748f"], - ["#9ccfd8", "#c4a7e7"], - ["#c4a7e7", "#eb6f92"], - ["#c4a7e7", "#f6c177"], - ["#c4a7e7", "#ebbcba"], - ["#c4a7e7", "#31748f"], - ["#c4a7e7", "#9ccfd8"], -]; - -const actualSize = size - margin * 2; -const cellSize = actualSize / n; -const sideN = Math.floor(n / 2); - -/** - * Generate buffer of an identicon by seed - */ -export function genIdenticon(seed: string, stream: WriteStream): Promise<void> { - const rand = gen.create(seed); - const canvas = p.make(size, size, undefined); - const ctx = canvas.getContext("2d"); - - const bgColors = colors[rand(colors.length)]; - - const bg = ctx.createLinearGradient(0, 0, size, size); - bg.addColorStop(0, bgColors[0]); - bg.addColorStop(1, bgColors[1]); - - ctx.fillStyle = bg; - ctx.beginPath(); - ctx.fillRect(0, 0, size, size); - - ctx.fillStyle = "#ffffff"; - - // side bitmap (filled by false) - const side: boolean[][] = new Array(sideN); - for (let i = 0; i < side.length; i++) { - side[i] = new Array(n).fill(false); - } - - // 1*n (filled by false) - const center: boolean[] = new Array(n).fill(false); - - for (let x = 0; x < side.length; x++) { - for (let y = 0; y < side[x].length; y++) { - side[x][y] = rand(3) === 0; - } - } - - for (let i = 0; i < center.length; i++) { - center[i] = rand(3) === 0; - } - - // Draw - for (let x = 0; x < n; x++) { - for (let y = 0; y < n; y++) { - const isXCenter = x === (n - 1) / 2; - if (isXCenter && !center[y]) continue; - - const isLeftSide = x < (n - 1) / 2; - if (isLeftSide && !side[x][y]) continue; - - const isRightSide = x > (n - 1) / 2; - if (isRightSide && !side[sideN - (x - sideN)][y]) continue; - - const actualX = margin + cellSize * x; - const actualY = margin + cellSize * y; - ctx.beginPath(); - ctx.fillRect(actualX, actualY, cellSize, cellSize); - } - } - - return p.encodePNGToStream(canvas, stream); -} diff --git a/packages/backend/src/misc/gen-key-pair.ts b/packages/backend/src/misc/gen-key-pair.ts deleted file mode 100644 index 8ae4175e30..0000000000 --- a/packages/backend/src/misc/gen-key-pair.ts +++ /dev/null @@ -1,42 +0,0 @@ -import * as crypto from "node:crypto"; -import * as util from "node:util"; - -const generateKeyPair = util.promisify(crypto.generateKeyPair); - -export async function genRsaKeyPair(modulusLength = 2048) { - return await generateKeyPair("rsa", { - modulusLength, - publicKeyEncoding: { - type: "spki", - format: "pem", - }, - privateKeyEncoding: { - type: "pkcs8", - format: "pem", - cipher: undefined, - passphrase: undefined, - }, - }); -} - -export async function genEcKeyPair( - namedCurve: - | "prime256v1" - | "secp384r1" - | "secp521r1" - | "curve25519" = "prime256v1", -) { - return await generateKeyPair("ec", { - namedCurve, - publicKeyEncoding: { - type: "spki", - format: "pem", - }, - privateKeyEncoding: { - type: "pkcs8", - format: "pem", - cipher: undefined, - passphrase: undefined, - }, - }); -} diff --git a/packages/backend/src/misc/get-file-info.ts b/packages/backend/src/misc/get-file-info.ts deleted file mode 100644 index a63de286ea..0000000000 --- a/packages/backend/src/misc/get-file-info.ts +++ /dev/null @@ -1,443 +0,0 @@ -import * as fs from "node:fs"; -import * as crypto from "node:crypto"; -import { join } from "node:path"; -import * as stream from "node:stream"; -import * as util from "node:util"; -import { FSWatcher } from "chokidar"; -import { fileTypeFromFile } from "file-type"; -import FFmpeg from "fluent-ffmpeg"; -import isSvg from "is-svg"; -import probeImageSize from "probe-image-size"; -import { type predictionType } from "nsfwjs"; -import sharp from "sharp"; -import { encode } from "blurhash"; -import { detectSensitive } from "@/services/detect-sensitive.js"; -import { createTempDir } from "./create-temp.js"; - -const pipeline = util.promisify(stream.pipeline); - -export type FileInfo = { - size: number; - md5: string; - type: { - mime: string; - ext: string | null; - }; - width?: number; - height?: number; - orientation?: number; - blurhash?: string; - sensitive: boolean; - porn: boolean; - warnings: string[]; -}; - -const TYPE_OCTET_STREAM = { - mime: "application/octet-stream", - ext: null, -}; - -const TYPE_SVG = { - mime: "image/svg+xml", - ext: "svg", -}; - -/** - * Get file information - */ -export async function getFileInfo( - path: string, - opts: { - skipSensitiveDetection: boolean; - sensitiveThreshold?: number; - sensitiveThresholdForPorn?: number; - enableSensitiveMediaDetectionForVideos?: boolean; - }, -): Promise<FileInfo> { - const warnings = [] as string[]; - - const size = await getFileSize(path); - const md5 = await calcHash(path); - - let type = await detectType(path); - - // image dimensions - let width: number | undefined; - let height: number | undefined; - let orientation: number | undefined; - - if ( - [ - "image/jpeg", - "image/gif", - "image/png", - "image/apng", - "image/webp", - "image/bmp", - "image/tiff", - "image/svg+xml", - "image/vnd.adobe.photoshop", - "image/avif", - ].includes(type.mime) - ) { - const imageSize = await detectImageSize(path).catch((e) => { - warnings.push(`detectImageSize failed: ${e}`); - return undefined; - }); - - // うまく判定できない画像は octet-stream にする - if (!imageSize) { - warnings.push("cannot detect image dimensions"); - type = TYPE_OCTET_STREAM; - } else if (imageSize.wUnits === "px") { - width = imageSize.width; - height = imageSize.height; - orientation = imageSize.orientation; - - // 制限を超えている画像は octet-stream にする - if (imageSize.width > 16383 || imageSize.height > 16383) { - warnings.push("image dimensions exceeds limits"); - type = TYPE_OCTET_STREAM; - } - } else { - warnings.push(`unsupported unit type: ${imageSize.wUnits}`); - } - } - - let blurhash: string | undefined; - - if ( - [ - "image/jpeg", - "image/gif", - "image/png", - "image/apng", - "image/webp", - "image/svg+xml", - "image/avif", - ].includes(type.mime) - ) { - blurhash = await getBlurhash(path).catch((e) => { - warnings.push(`getBlurhash failed: ${e}`); - return undefined; - }); - } - - let sensitive = false; - let porn = false; - - if (!opts.skipSensitiveDetection) { - await detectSensitivity( - path, - type.mime, - opts.sensitiveThreshold ?? 0.5, - opts.sensitiveThresholdForPorn ?? 0.75, - opts.enableSensitiveMediaDetectionForVideos ?? false, - ).then( - (value) => { - [sensitive, porn] = value; - }, - (error) => { - warnings.push(`detectSensitivity failed: ${error}`); - }, - ); - } - - return { - size, - md5, - type, - width, - height, - orientation, - blurhash, - sensitive, - porn, - warnings, - }; -} - -async function detectSensitivity( - source: string, - mime: string, - sensitiveThreshold: number, - sensitiveThresholdForPorn: number, - analyzeVideo: boolean, -): Promise<[sensitive: boolean, porn: boolean]> { - let sensitive = false; - let porn = false; - - function judgePrediction( - result: readonly predictionType[], - ): [sensitive: boolean, porn: boolean] { - let sensitive = false; - let porn = false; - - if ( - (result.find((x) => x.className === "Sexy")?.probability ?? 0) > - sensitiveThreshold - ) - sensitive = true; - if ( - (result.find((x) => x.className === "Hentai")?.probability ?? 0) > - sensitiveThreshold - ) - sensitive = true; - if ( - (result.find((x) => x.className === "Porn")?.probability ?? 0) > - sensitiveThreshold - ) - sensitive = true; - - if ( - (result.find((x) => x.className === "Porn")?.probability ?? 0) > - sensitiveThresholdForPorn - ) - porn = true; - - return [sensitive, porn]; - } - - if (["image/jpeg", "image/png", "image/webp"].includes(mime)) { - const result = await detectSensitive(source); - if (result) { - [sensitive, porn] = judgePrediction(result); - } - } else if ( - analyzeVideo && - (mime === "image/apng" || mime.startsWith("video/")) - ) { - const [outDir, disposeOutDir] = await createTempDir(); - try { - const command = FFmpeg() - .input(source) - .inputOptions([ - "-skip_frame", - "nokey", // 可能ならキーフレームのみを取得してほしいとする(そうなるとは限らない) - "-lowres", - "3", // 元の画質でデコードする必要はないので 1/8 画質でデコードしてもよいとする(そうなるとは限らない) - ]) - .noAudio() - .videoFilters([ - { - filter: "select", // フレームのフィルタリング - options: { - e: "eq(pict_type,PICT_TYPE_I)", // I-Frame のみをフィルタする(VP9 とかはデコードしてみないとわからないっぽい) - }, - }, - { - filter: "blackframe", // 暗いフレームの検出 - options: { - amount: "0", // 暗さに関わらず全てのフレームで測定値を取る - }, - }, - { - filter: "metadata", - options: { - mode: "select", // フレーム選択モード - key: "lavfi.blackframe.pblack", // フレームにおける暗部の百分率(前のフィルタからのメタデータを参照する) - value: "50", - function: "less", // 50% 未満のフレームを選択する(50% 以上暗部があるフレームだと誤検知を招くかもしれないので) - }, - }, - { - filter: "scale", - options: { - w: 299, - h: 299, - }, - }, - ]) - .format("image2") - .output(join(outDir, "%d.png")) - .outputOptions(["-vsync", "0"]); // 可変フレームレートにすることで穴埋めをさせない - const results: ReturnType<typeof judgePrediction>[] = []; - let frameIndex = 0; - let targetIndex = 0; - let nextIndex = 1; - for await (const path of asyncIterateFrames(outDir, command)) { - try { - const index = frameIndex++; - if (index !== targetIndex) { - continue; - } - targetIndex = nextIndex; - nextIndex += index; // fibonacci sequence によってフレーム数制限を掛ける - const result = await detectSensitive(path); - if (result) { - results.push(judgePrediction(result)); - } - } finally { - fs.promises.unlink(path); - } - } - sensitive = - results.filter((x) => x[0]).length >= - Math.ceil(results.length * sensitiveThreshold); - porn = - results.filter((x) => x[1]).length >= - Math.ceil(results.length * sensitiveThresholdForPorn); - } finally { - disposeOutDir(); - } - } - - return [sensitive, porn]; -} - -async function* asyncIterateFrames( - cwd: string, - command: FFmpeg.FfmpegCommand, -): AsyncGenerator<string, void> { - const watcher = new FSWatcher({ - cwd, - disableGlobbing: true, - }); - let finished = false; - command.once("end", () => { - finished = true; - watcher.close(); - }); - command.run(); - for (let i = 1; true; i++) { - const current = `${i}.png`; - const next = `${i + 1}.png`; - const framePath = join(cwd, current); - if (await exists(join(cwd, next))) { - yield framePath; - } else if (!finished) { - watcher.add(next); - await new Promise<void>((resolve, reject) => { - watcher.on("add", function onAdd(path) { - if (path === next) { - // 次フレームの書き出しが始まっているなら、現在フレームの書き出しは終わっている - watcher.unwatch(current); - watcher.off("add", onAdd); - resolve(); - } - }); - command.once("end", resolve); // 全てのフレームを処理し終わったなら、最終フレームである現在フレームの書き出しは終わっている - command.once("error", reject); - }); - yield framePath; - } else if (await exists(framePath)) { - yield framePath; - } else { - return; - } - } -} - -function exists(path: string): Promise<boolean> { - return fs.promises.access(path).then( - () => true, - () => false, - ); -} - -/** - * Detect MIME Type and extension - */ -export async function detectType(path: string): Promise<{ - mime: string; - ext: string | null; -}> { - // Check 0 byte - const fileSize = await getFileSize(path); - if (fileSize === 0) { - return TYPE_OCTET_STREAM; - } - - const type = await fileTypeFromFile(path); - - if (type) { - // XMLはSVGかもしれない - if (type.mime === "application/xml" && (await checkSvg(path))) { - return TYPE_SVG; - } - - return { - mime: type.mime, - ext: type.ext, - }; - } - - // 種類が不明でもSVGかもしれない - if (await checkSvg(path)) { - return TYPE_SVG; - } - - // それでも種類が不明なら application/octet-stream にする - return TYPE_OCTET_STREAM; -} - -/** - * Check the file is SVG or not - */ -export async function checkSvg(path: string) { - try { - const size = await getFileSize(path); - if (size > 1 * 1024 * 1024) return false; - return isSvg(fs.readFileSync(path)); - } catch { - return false; - } -} - -/** - * Get file size - */ -export async function getFileSize(path: string): Promise<number> { - const getStat = util.promisify(fs.stat); - return (await getStat(path)).size; -} - -/** - * Calculate MD5 hash - */ -async function calcHash(path: string): Promise<string> { - const hash = crypto.createHash("md5").setEncoding("hex"); - await pipeline(fs.createReadStream(path), hash); - return hash.read(); -} - -/** - * Detect dimensions of image - */ -async function detectImageSize(path: string): Promise<{ - width: number; - height: number; - wUnits: string; - hUnits: string; - orientation?: number; -}> { - const readable = fs.createReadStream(path); - const imageSize = await probeImageSize(readable); - readable.destroy(); - return imageSize; -} - -/** - * Calculate average color of image - */ -function getBlurhash(path: string): Promise<string> { - return new Promise((resolve, reject) => { - sharp(path) - .raw() - .ensureAlpha() - .resize(64, 64, { fit: "inside" }) - .toBuffer((err, buffer, { width, height }) => { - if (err) return reject(err); - - let hash; - - try { - hash = encode(new Uint8ClampedArray(buffer), width, height, 7, 7); - } catch (e) { - return reject(e); - } - - resolve(hash); - }); - }); -} diff --git a/packages/backend/src/misc/get-ip-hash.ts b/packages/backend/src/misc/get-ip-hash.ts deleted file mode 100644 index 3bafaee5df..0000000000 --- a/packages/backend/src/misc/get-ip-hash.ts +++ /dev/null @@ -1,14 +0,0 @@ -import IPCIDR from "ip-cidr"; - -export function getIpHash(ip: string) { - try { - // because a single person may control many IPv6 addresses, - // only a /64 subnet prefix of any IP will be taken into account. - // (this means for IPv4 the entire address is used) - const prefix = IPCIDR.createAddress(ip).mask(64); - return `ip-${BigInt(`0b${prefix}`).toString(36)}`; - } catch (e) { - const prefix = IPCIDR.createAddress(ip.replace(/:[0-9]+$/, "")).mask(64); - return `ip-${BigInt(`0b${prefix}`).toString(36)}`; - } -} diff --git a/packages/backend/src/misc/get-note-summary.ts b/packages/backend/src/misc/get-note-summary.ts deleted file mode 100644 index 446e3fc140..0000000000 --- a/packages/backend/src/misc/get-note-summary.ts +++ /dev/null @@ -1,52 +0,0 @@ -import type { Packed } from "./schema.js"; - -/** - * 投稿を表す文字列を取得します。 - * @param {*} note (packされた)投稿 - */ -export const getNoteSummary = (note: Packed<"Note">): string => { - if (note.deletedAt) { - return "❌"; - } - - let summary = ""; - - // 本文 - if (note.cw != null) { - summary += note.cw; - } else { - summary += note.text ? note.text : ""; - } - - // ファイルが添付されているとき - if ((note.files || []).length !== 0) { - summary += ` (📎${note.files!.length})`; - } - - // 投票が添付されているとき - if (note.poll) { - summary += " (📊)"; - } - - /* - // 返信のとき - if (note.replyId) { - if (note.reply) { - summary += `\n\nRE: ${getNoteSummary(note.reply)}`; - } else { - summary += '\n\nRE: ...'; - } - } - - // Renoteのとき - if (note.renoteId) { - if (note.renote) { - summary += `\n\nRN: ${getNoteSummary(note.renote)}`; - } else { - summary += '\n\nRN: ...'; - } - } - */ - - return summary.trim(); -}; diff --git a/packages/backend/src/misc/get-reaction-emoji.ts b/packages/backend/src/misc/get-reaction-emoji.ts deleted file mode 100644 index 71521c4ae8..0000000000 --- a/packages/backend/src/misc/get-reaction-emoji.ts +++ /dev/null @@ -1,28 +0,0 @@ -export default function (reaction: string): string { - switch (reaction) { - case "like": - return "👍"; - case "love": - return "❤️"; - case "laugh": - return "😆"; - case "hmm": - return "🤔"; - case "surprise": - return "😮"; - case "congrats": - return "🎉"; - case "angry": - return "💢"; - case "confused": - return "😥"; - case "rip": - return "😇"; - case "pudding": - return "🍮"; - case "star": - return "⭐"; - default: - return reaction; - } -} diff --git a/packages/backend/src/misc/hard-limits.ts b/packages/backend/src/misc/hard-limits.ts deleted file mode 100644 index 51d2c0f5d2..0000000000 --- a/packages/backend/src/misc/hard-limits.ts +++ /dev/null @@ -1,13 +0,0 @@ -// If you change DB_* values, you must also change the DB schema. - -/** - * Maximum note text length that can be stored in DB. - * Surrogate pairs count as one - */ -export const DB_MAX_NOTE_TEXT_LENGTH = 8192; - -/** - * Maximum image description length that can be stored in DB. - * Surrogate pairs count as one - */ -export const DB_MAX_IMAGE_COMMENT_LENGTH = 8192; diff --git a/packages/backend/src/misc/i18n.ts b/packages/backend/src/misc/i18n.ts deleted file mode 100644 index 742bdb0f69..0000000000 --- a/packages/backend/src/misc/i18n.ts +++ /dev/null @@ -1,29 +0,0 @@ -export class I18n<T extends Record<string, any>> { - public locale: T; - - constructor(locale: T) { - this.locale = locale; - - //#region BIND - this.t = this.t.bind(this); - //#endregion - } - - // string にしているのは、ドット区切りでのパス指定を許可するため - // なるべくこのメソッド使うよりもlocale直接参照の方がvueのキャッシュ効いてパフォーマンスが良いかも - public t(key: string, args?: Record<string, any>): string { - try { - let str = key.split(".").reduce((o, i) => o[i], this.locale) as string; - - if (args) { - for (const [k, v] of Object.entries(args)) { - str = str.replace(`{${k}}`, v); - } - } - return str; - } catch (e) { - console.warn(`missing localization '${key}'`); - return key; - } - } -} diff --git a/packages/backend/src/misc/id/aid.ts b/packages/backend/src/misc/id/aid.ts deleted file mode 100644 index a12360360b..0000000000 --- a/packages/backend/src/misc/id/aid.ts +++ /dev/null @@ -1,25 +0,0 @@ -// AID -// 長さ8の[2000年1月1日からの経過ミリ秒をbase36でエンコードしたもの] + 長さ2の[ノイズ文字列] - -import * as crypto from "node:crypto"; - -const TIME2000 = 946684800000; -let counter = crypto.randomBytes(2).readUInt16LE(0); - -function getTime(time: number) { - time = time - TIME2000; - if (time < 0) time = 0; - - return time.toString(36).padStart(8, "0"); -} - -function getNoise() { - return counter.toString(36).padStart(2, "0").slice(-2); -} - -export function genAid(date: Date): string { - const t = date.getTime(); - if (isNaN(t)) throw "Failed to create AID: Invalid Date"; - counter++; - return getTime(t) + getNoise(); -} diff --git a/packages/backend/src/misc/id/meid.ts b/packages/backend/src/misc/id/meid.ts deleted file mode 100644 index ee78eb8d14..0000000000 --- a/packages/backend/src/misc/id/meid.ts +++ /dev/null @@ -1,26 +0,0 @@ -const CHARS = "0123456789abcdef"; - -function getTime(time: number) { - if (time < 0) time = 0; - if (time === 0) { - return CHARS[0]; - } - - time += 0x800000000000; - - return time.toString(16).padStart(12, CHARS[0]); -} - -function getRandom() { - let str = ""; - - for (let i = 0; i < 12; i++) { - str += CHARS[Math.floor(Math.random() * CHARS.length)]; - } - - return str; -} - -export function genMeid(date: Date): string { - return getTime(date.getTime()) + getRandom(); -} diff --git a/packages/backend/src/misc/id/meidg.ts b/packages/backend/src/misc/id/meidg.ts deleted file mode 100644 index 4fd39a8b41..0000000000 --- a/packages/backend/src/misc/id/meidg.ts +++ /dev/null @@ -1,28 +0,0 @@ -const CHARS = "0123456789abcdef"; - -// 4bit Fixed hex value 'g' -// 44bit UNIX Time ms in Hex -// 48bit Random value in Hex - -function getTime(time: number) { - if (time < 0) time = 0; - if (time === 0) { - return CHARS[0]; - } - - return time.toString(16).padStart(11, CHARS[0]); -} - -function getRandom() { - let str = ""; - - for (let i = 0; i < 12; i++) { - str += CHARS[Math.floor(Math.random() * CHARS.length)]; - } - - return str; -} - -export function genMeidg(date: Date): string { - return `g${getTime(date.getTime())}${getRandom()}`; -} diff --git a/packages/backend/src/misc/id/object-id.ts b/packages/backend/src/misc/id/object-id.ts deleted file mode 100644 index 45822f0acc..0000000000 --- a/packages/backend/src/misc/id/object-id.ts +++ /dev/null @@ -1,26 +0,0 @@ -const CHARS = "0123456789abcdef"; - -function getTime(time: number) { - if (time < 0) time = 0; - if (time === 0) { - return CHARS[0]; - } - - time = Math.floor(time / 1000); - - return time.toString(16).padStart(8, CHARS[0]); -} - -function getRandom() { - let str = ""; - - for (let i = 0; i < 16; i++) { - str += CHARS[Math.floor(Math.random() * CHARS.length)]; - } - - return str; -} - -export function genObjectId(date: Date): string { - return getTime(date.getTime()) + getRandom(); -} diff --git a/packages/backend/src/misc/identifiable-error.ts b/packages/backend/src/misc/identifiable-error.ts deleted file mode 100644 index be6eb5bd8d..0000000000 --- a/packages/backend/src/misc/identifiable-error.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * ID付きエラー - */ -export class IdentifiableError extends Error { - public message: string; - public id: string; - - constructor(id: string, message?: string) { - super(message); - this.message = message || ""; - this.id = id; - } -} diff --git a/packages/backend/src/misc/is-duplicate-key-value-error.ts b/packages/backend/src/misc/is-duplicate-key-value-error.ts deleted file mode 100644 index 18d22bb77c..0000000000 --- a/packages/backend/src/misc/is-duplicate-key-value-error.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function isDuplicateKeyValueError(e: unknown | Error): boolean { - return (e as Error).message?.startsWith("duplicate key value"); -} diff --git a/packages/backend/src/misc/is-instance-muted.ts b/packages/backend/src/misc/is-instance-muted.ts deleted file mode 100644 index 1547d4555c..0000000000 --- a/packages/backend/src/misc/is-instance-muted.ts +++ /dev/null @@ -1,21 +0,0 @@ -import type { Packed } from "./schema.js"; - -export function isInstanceMuted( - note: Packed<"Note">, - mutedInstances: Set<string>, -): boolean { - if (mutedInstances.has(note?.user?.host ?? "")) return true; - if (mutedInstances.has(note?.reply?.user?.host ?? "")) return true; - if (mutedInstances.has(note?.renote?.user?.host ?? "")) return true; - - return false; -} - -export function isUserFromMutedInstance( - notif: Packed<"Notification">, - mutedInstances: Set<string>, -): boolean { - if (mutedInstances.has(notif?.user?.host ?? "")) return true; - - return false; -} diff --git a/packages/backend/src/misc/is-mime-image.ts b/packages/backend/src/misc/is-mime-image.ts deleted file mode 100644 index a8ba62ec20..0000000000 --- a/packages/backend/src/misc/is-mime-image.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { FILE_TYPE_BROWSERSAFE } from "@/const.js"; - -const dictionary = { - "safe-file": FILE_TYPE_BROWSERSAFE, - "sharp-convertible-image": [ - "image/jpeg", - "image/png", - "image/gif", - "image/apng", - "image/vnd.mozilla.apng", - "image/webp", - "image/svg+xml", - "image/avif", - ], -}; - -export const isMimeImage = ( - mime: string, - type: keyof typeof dictionary, -): boolean => dictionary[type].includes(mime); diff --git a/packages/backend/src/misc/is-quote.ts b/packages/backend/src/misc/is-quote.ts deleted file mode 100644 index fe83a56a55..0000000000 --- a/packages/backend/src/misc/is-quote.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { Note } from "@/models/entities/note.js"; - -export default function (note: Note): boolean { - return ( - note.renoteId != null && - (note.text != null || - note.hasPoll || - (note.fileIds != null && note.fileIds.length > 0)) - ); -} diff --git a/packages/backend/src/misc/is-user-related.ts b/packages/backend/src/misc/is-user-related.ts deleted file mode 100644 index 64591cfef3..0000000000 --- a/packages/backend/src/misc/is-user-related.ts +++ /dev/null @@ -1,7 +0,0 @@ -export function isUserRelated(note: any, ids: Set<string>): boolean { - if (ids.has(note.userId)) return true; // note author is muted - if (note.mentions?.some((user: string) => ids.has(user))) return true; // any of mentioned users are muted - if (note.reply && isUserRelated(note.reply, ids)) return true; // also check reply target - if (note.renote && isUserRelated(note.renote, ids)) return true; // also check renote target - return false; -} diff --git a/packages/backend/src/misc/keypair-store.ts b/packages/backend/src/misc/keypair-store.ts deleted file mode 100644 index 4551bfd988..0000000000 --- a/packages/backend/src/misc/keypair-store.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { UserKeypairs } from "@/models/index.js"; -import type { User } from "@/models/entities/user.js"; -import type { UserKeypair } from "@/models/entities/user-keypair.js"; -import { Cache } from "./cache.js"; - -const cache = new Cache<UserKeypair>(Infinity); - -export async function getUserKeypair(userId: User["id"]): Promise<UserKeypair> { - return await cache.fetch(userId, () => - UserKeypairs.findOneByOrFail({ userId: userId }), - ); -} diff --git a/packages/backend/src/misc/langmap.ts b/packages/backend/src/misc/langmap.ts deleted file mode 100644 index 106130d3c3..0000000000 --- a/packages/backend/src/misc/langmap.ts +++ /dev/null @@ -1,666 +0,0 @@ -// TODO: sharedに置いてフロントエンドのと統合したい -export const langmap = { - ach: { - nativeName: "Lwo", - }, - ady: { - nativeName: "Адыгэбзэ", - }, - af: { - nativeName: "Afrikaans", - }, - "af-NA": { - nativeName: "Afrikaans (Namibia)", - }, - "af-ZA": { - nativeName: "Afrikaans (South Africa)", - }, - ak: { - nativeName: "Tɕɥi", - }, - ar: { - nativeName: "العربية", - }, - "ar-AR": { - nativeName: "العربية", - }, - "ar-MA": { - nativeName: "العربية", - }, - "ar-SA": { - nativeName: "العربية (السعودية)", - }, - "ay-BO": { - nativeName: "Aymar aru", - }, - az: { - nativeName: "Azərbaycan dili", - }, - "az-AZ": { - nativeName: "Azərbaycan dili", - }, - "be-BY": { - nativeName: "Беларуская", - }, - bg: { - nativeName: "Български", - }, - "bg-BG": { - nativeName: "Български", - }, - bn: { - nativeName: "বাংলা", - }, - "bn-IN": { - nativeName: "বাংলা (ভারত)", - }, - "bn-BD": { - nativeName: "বাংলা(বাংলাদেশ)", - }, - br: { - nativeName: "Brezhoneg", - }, - "bs-BA": { - nativeName: "Bosanski", - }, - ca: { - nativeName: "Català", - }, - "ca-ES": { - nativeName: "Català", - }, - cak: { - nativeName: "Maya Kaqchikel", - }, - "ck-US": { - nativeName: "ᏣᎳᎩ (tsalagi)", - }, - cs: { - nativeName: "Čeština", - }, - "cs-CZ": { - nativeName: "Čeština", - }, - cy: { - nativeName: "Cymraeg", - }, - "cy-GB": { - nativeName: "Cymraeg", - }, - da: { - nativeName: "Dansk", - }, - "da-DK": { - nativeName: "Dansk", - }, - de: { - nativeName: "Deutsch", - }, - "de-AT": { - nativeName: "Deutsch (Österreich)", - }, - "de-DE": { - nativeName: "Deutsch (Deutschland)", - }, - "de-CH": { - nativeName: "Deutsch (Schweiz)", - }, - dsb: { - nativeName: "Dolnoserbšćina", - }, - el: { - nativeName: "Ελληνικά", - }, - "el-GR": { - nativeName: "Ελληνικά", - }, - en: { - nativeName: "English", - }, - "en-GB": { - nativeName: "English (UK)", - }, - "en-AU": { - nativeName: "English (Australia)", - }, - "en-CA": { - nativeName: "English (Canada)", - }, - "en-IE": { - nativeName: "English (Ireland)", - }, - "en-IN": { - nativeName: "English (India)", - }, - "en-PI": { - nativeName: "English (Pirate)", - }, - "en-SG": { - nativeName: "English (Singapore)", - }, - "en-UD": { - nativeName: "English (Upside Down)", - }, - "en-US": { - nativeName: "English (US)", - }, - "en-ZA": { - nativeName: "English (South Africa)", - }, - "en@pirate": { - nativeName: "English (Pirate)", - }, - eo: { - nativeName: "Esperanto", - }, - "eo-EO": { - nativeName: "Esperanto", - }, - es: { - nativeName: "Español", - }, - "es-AR": { - nativeName: "Español (Argentine)", - }, - "es-419": { - nativeName: "Español (Latinoamérica)", - }, - "es-CL": { - nativeName: "Español (Chile)", - }, - "es-CO": { - nativeName: "Español (Colombia)", - }, - "es-EC": { - nativeName: "Español (Ecuador)", - }, - "es-ES": { - nativeName: "Español (España)", - }, - "es-LA": { - nativeName: "Español (Latinoamérica)", - }, - "es-NI": { - nativeName: "Español (Nicaragua)", - }, - "es-MX": { - nativeName: "Español (México)", - }, - "es-US": { - nativeName: "Español (Estados Unidos)", - }, - "es-VE": { - nativeName: "Español (Venezuela)", - }, - et: { - nativeName: "eesti keel", - }, - "et-EE": { - nativeName: "Eesti (Estonia)", - }, - eu: { - nativeName: "Euskara", - }, - "eu-ES": { - nativeName: "Euskara", - }, - fa: { - nativeName: "فارسی", - }, - "fa-IR": { - nativeName: "فارسی", - }, - "fb-LT": { - nativeName: "Leet Speak", - }, - ff: { - nativeName: "Fulah", - }, - fi: { - nativeName: "Suomi", - }, - "fi-FI": { - nativeName: "Suomi", - }, - fo: { - nativeName: "Føroyskt", - }, - "fo-FO": { - nativeName: "Føroyskt (Færeyjar)", - }, - fr: { - nativeName: "Français", - }, - "fr-CA": { - nativeName: "Français (Canada)", - }, - "fr-FR": { - nativeName: "Français (France)", - }, - "fr-BE": { - nativeName: "Français (Belgique)", - }, - "fr-CH": { - nativeName: "Français (Suisse)", - }, - "fy-NL": { - nativeName: "Frysk", - }, - ga: { - nativeName: "Gaeilge", - }, - "ga-IE": { - nativeName: "Gaeilge", - }, - gd: { - nativeName: "Gàidhlig", - }, - gl: { - nativeName: "Galego", - }, - "gl-ES": { - nativeName: "Galego", - }, - "gn-PY": { - nativeName: "Avañe'ẽ", - }, - "gu-IN": { - nativeName: "ગુજરાતી", - }, - gv: { - nativeName: "Gaelg", - }, - "gx-GR": { - nativeName: "Ἑλληνική ἀρχαία", - }, - he: { - nativeName: "עברית", - }, - "he-IL": { - nativeName: "עברית", - }, - hi: { - nativeName: "हिन्दी", - }, - "hi-IN": { - nativeName: "हिन्दी", - }, - hr: { - nativeName: "Hrvatski", - }, - "hr-HR": { - nativeName: "Hrvatski", - }, - hsb: { - nativeName: "Hornjoserbšćina", - }, - ht: { - nativeName: "Kreyòl", - }, - hu: { - nativeName: "Magyar", - }, - "hu-HU": { - nativeName: "Magyar", - }, - hy: { - nativeName: "Հայերեն", - }, - "hy-AM": { - nativeName: "Հայերեն (Հայաստան)", - }, - id: { - nativeName: "Bahasa Indonesia", - }, - "id-ID": { - nativeName: "Bahasa Indonesia", - }, - is: { - nativeName: "Íslenska", - }, - "is-IS": { - nativeName: "Íslenska (Iceland)", - }, - it: { - nativeName: "Italiano", - }, - "it-IT": { - nativeName: "Italiano", - }, - ja: { - nativeName: "日本語", - }, - "ja-JP": { - nativeName: "日本語 (日本)", - }, - "jv-ID": { - nativeName: "Basa Jawa", - }, - "ka-GE": { - nativeName: "ქართული", - }, - "kk-KZ": { - nativeName: "Қазақша", - }, - km: { - nativeName: "ភាសាខ្មែរ", - }, - kl: { - nativeName: "kalaallisut", - }, - "km-KH": { - nativeName: "ភាសាខ្មែរ", - }, - kab: { - nativeName: "Taqbaylit", - }, - kn: { - nativeName: "ಕನ್ನಡ", - }, - "kn-IN": { - nativeName: "ಕನ್ನಡ (India)", - }, - ko: { - nativeName: "한국어", - }, - "ko-KR": { - nativeName: "한국어 (한국)", - }, - "ku-TR": { - nativeName: "Kurdî", - }, - kw: { - nativeName: "Kernewek", - }, - la: { - nativeName: "Latin", - }, - "la-VA": { - nativeName: "Latin", - }, - lb: { - nativeName: "Lëtzebuergesch", - }, - "li-NL": { - nativeName: "Lèmbörgs", - }, - lt: { - nativeName: "Lietuvių", - }, - "lt-LT": { - nativeName: "Lietuvių", - }, - lv: { - nativeName: "Latviešu", - }, - "lv-LV": { - nativeName: "Latviešu", - }, - mai: { - nativeName: "मैथिली, মৈথিলী", - }, - "mg-MG": { - nativeName: "Malagasy", - }, - mk: { - nativeName: "Македонски", - }, - "mk-MK": { - nativeName: "Македонски (Македонски)", - }, - ml: { - nativeName: "മലയാളം", - }, - "ml-IN": { - nativeName: "മലയാളം", - }, - "mn-MN": { - nativeName: "Монгол", - }, - mr: { - nativeName: "मराठी", - }, - "mr-IN": { - nativeName: "मराठी", - }, - ms: { - nativeName: "Bahasa Melayu", - }, - "ms-MY": { - nativeName: "Bahasa Melayu", - }, - mt: { - nativeName: "Malti", - }, - "mt-MT": { - nativeName: "Malti", - }, - my: { - nativeName: "ဗမာစကာ", - }, - no: { - nativeName: "Norsk", - }, - nb: { - nativeName: "Norsk (bokmål)", - }, - "nb-NO": { - nativeName: "Norsk (bokmål)", - }, - ne: { - nativeName: "नेपाली", - }, - "ne-NP": { - nativeName: "नेपाली", - }, - nl: { - nativeName: "Nederlands", - }, - "nl-BE": { - nativeName: "Nederlands (België)", - }, - "nl-NL": { - nativeName: "Nederlands (Nederland)", - }, - "nn-NO": { - nativeName: "Norsk (nynorsk)", - }, - oc: { - nativeName: "Occitan", - }, - "or-IN": { - nativeName: "ଓଡ଼ିଆ", - }, - pa: { - nativeName: "ਪੰਜਾਬੀ", - }, - "pa-IN": { - nativeName: "ਪੰਜਾਬੀ (ਭਾਰਤ ਨੂੰ)", - }, - pl: { - nativeName: "Polski", - }, - "pl-PL": { - nativeName: "Polski", - }, - "ps-AF": { - nativeName: "پښتو", - }, - pt: { - nativeName: "Português", - }, - "pt-BR": { - nativeName: "Português (Brasil)", - }, - "pt-PT": { - nativeName: "Português (Portugal)", - }, - "qu-PE": { - nativeName: "Qhichwa", - }, - "rm-CH": { - nativeName: "Rumantsch", - }, - ro: { - nativeName: "Română", - }, - "ro-RO": { - nativeName: "Română", - }, - ru: { - nativeName: "Русский", - }, - "ru-RU": { - nativeName: "Русский", - }, - "sa-IN": { - nativeName: "संस्कृतम्", - }, - "se-NO": { - nativeName: "Davvisámegiella", - }, - sh: { - nativeName: "српскохрватски", - }, - "si-LK": { - nativeName: "සිංහල", - }, - sk: { - nativeName: "Slovenčina", - }, - "sk-SK": { - nativeName: "Slovenčina (Slovakia)", - }, - sl: { - nativeName: "Slovenščina", - }, - "sl-SI": { - nativeName: "Slovenščina", - }, - "so-SO": { - nativeName: "Soomaaliga", - }, - sq: { - nativeName: "Shqip", - }, - "sq-AL": { - nativeName: "Shqip", - }, - sr: { - nativeName: "Српски", - }, - "sr-RS": { - nativeName: "Српски (Serbia)", - }, - su: { - nativeName: "Basa Sunda", - }, - sv: { - nativeName: "Svenska", - }, - "sv-SE": { - nativeName: "Svenska", - }, - sw: { - nativeName: "Kiswahili", - }, - "sw-KE": { - nativeName: "Kiswahili", - }, - ta: { - nativeName: "தமிழ்", - }, - "ta-IN": { - nativeName: "தமிழ்", - }, - te: { - nativeName: "తెలుగు", - }, - "te-IN": { - nativeName: "తెలుగు", - }, - tg: { - nativeName: "забо́ни тоҷикӣ́", - }, - "tg-TJ": { - nativeName: "тоҷикӣ", - }, - th: { - nativeName: "ภาษาไทย", - }, - "th-TH": { - nativeName: "ภาษาไทย (ประเทศไทย)", - }, - fil: { - nativeName: "Filipino", - }, - tlh: { - nativeName: "tlhIngan-Hol", - }, - tr: { - nativeName: "Türkçe", - }, - "tr-TR": { - nativeName: "Türkçe", - }, - "tt-RU": { - nativeName: "татарча", - }, - uk: { - nativeName: "Українська", - }, - "uk-UA": { - nativeName: "Українська", - }, - ur: { - nativeName: "اردو", - }, - "ur-PK": { - nativeName: "اردو", - }, - uz: { - nativeName: "O'zbek", - }, - "uz-UZ": { - nativeName: "O'zbek", - }, - vi: { - nativeName: "Tiếng Việt", - }, - "vi-VN": { - nativeName: "Tiếng Việt", - }, - "xh-ZA": { - nativeName: "isiXhosa", - }, - yi: { - nativeName: "ייִדיש", - }, - "yi-DE": { - nativeName: "ייִדיש (German)", - }, - zh: { - nativeName: "中文", - }, - "zh-Hans": { - nativeName: "中文简体", - }, - "zh-Hant": { - nativeName: "中文繁體", - }, - "zh-CN": { - nativeName: "中文(中国大陆)", - }, - "zh-HK": { - nativeName: "中文(香港)", - }, - "zh-SG": { - nativeName: "中文(新加坡)", - }, - "zh-TW": { - nativeName: "中文(台灣)", - }, - "zu-ZA": { - nativeName: "isiZulu", - }, -}; diff --git a/packages/backend/src/misc/normalize-for-search.ts b/packages/backend/src/misc/normalize-for-search.ts deleted file mode 100644 index 6882a1243e..0000000000 --- a/packages/backend/src/misc/normalize-for-search.ts +++ /dev/null @@ -1,6 +0,0 @@ -export function normalizeForSearch(tag: string): string { - // ref. - // - https://analytics-note.xyz/programming/unicode-normalization-forms/ - // - https://maku77.github.io/js/string/normalize.html - return tag.normalize("NFKC").toLowerCase(); -} diff --git a/packages/backend/src/misc/nyaize.ts b/packages/backend/src/misc/nyaize.ts deleted file mode 100644 index b85f1d918e..0000000000 --- a/packages/backend/src/misc/nyaize.ts +++ /dev/null @@ -1,21 +0,0 @@ -export function nyaize(text: string): string { - return ( - text - // ja-JP - .replaceAll("な", "にゃ") - .replaceAll("ナ", "ニャ") - .replaceAll("ナ", "ニャ") - // en-US - .replace(/(?<=n)a/gi, (x) => (x === "A" ? "YA" : "ya")) - .replace(/(?<=morn)ing/gi, (x) => (x === "ING" ? "YAN" : "yan")) - .replace(/(?<=every)one/gi, (x) => (x === "ONE" ? "NYAN" : "nyan")) - // ko-KR - .replace(/[나-낳]/g, (match) => - String.fromCharCode( - match.charCodeAt(0)! + "냐".charCodeAt(0) - "나".charCodeAt(0), - ), - ) - .replace(/(다$)|(다(?=\.))|(다(?= ))|(다(?=!))|(다(?=\?))/gm, "다냥") - .replace(/(야(?=\?))|(야$)|(야(?= ))/gm, "냥") - ); -} diff --git a/packages/backend/src/misc/password.ts b/packages/backend/src/misc/password.ts deleted file mode 100644 index c63f89f5c9..0000000000 --- a/packages/backend/src/misc/password.ts +++ /dev/null @@ -1,20 +0,0 @@ -import bcrypt from "bcryptjs"; -import * as argon2 from "argon2"; - -export async function hashPassword(password: string): Promise<string> { - return argon2.hash(password); -} - -export async function comparePassword( - password: string, - hash: string, -): Promise<boolean> { - if (isOldAlgorithm(hash)) return bcrypt.compare(password, hash); - - return argon2.verify(hash, password); -} - -export function isOldAlgorithm(hash: string): boolean { - // bcrypt hashes start with $2[ab]$ - return hash.startsWith("$2"); -} diff --git a/packages/backend/src/misc/populate-emojis.ts b/packages/backend/src/misc/populate-emojis.ts deleted file mode 100644 index 3f20f9f10d..0000000000 --- a/packages/backend/src/misc/populate-emojis.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { In, IsNull } from "typeorm"; -import { Emojis } from "@/models/index.js"; -import type { Emoji } from "@/models/entities/emoji.js"; -import type { Note } from "@/models/entities/note.js"; -import { Cache } from "./cache.js"; -import { isSelfHost, toPunyNullable } from "./convert-host.js"; -import { decodeReaction } from "./reaction-lib.js"; -import config from "@/config/index.js"; -import { query } from "@/prelude/url.js"; - -const cache = new Cache<Emoji | null>(1000 * 60 * 60 * 12); - -/** - * 添付用絵文字情報 - */ -type PopulatedEmoji = { - name: string; - url: string; -}; - -function normalizeHost( - src: string | undefined, - noteUserHost: string | null, -): string | null { - // クエリに使うホスト - let host = - src === "." - ? null // .はローカルホスト (ここがマッチするのはリアクションのみ) - : src === undefined - ? noteUserHost // ノートなどでホスト省略表記の場合はローカルホスト (ここがリアクションにマッチすることはない) - : isSelfHost(src) - ? null // 自ホスト指定 - : src || noteUserHost; // 指定されたホスト || ノートなどの所有者のホスト (こっちがリアクションにマッチすることはない) - - host = toPunyNullable(host); - - return host; -} - -function parseEmojiStr(emojiName: string, noteUserHost: string | null) { - const match = emojiName.match(/^(\w+)(?:@([\w.-]+))?$/); - if (!match) return { name: null, host: null }; - - const name = match[1]; - - // ホスト正規化 - const host = toPunyNullable(normalizeHost(match[2], noteUserHost)); - - return { name, host }; -} - -/** - * 添付用絵文字情報を解決する - * @param emojiName ノートやユーザープロフィールに添付された、またはリアクションのカスタム絵文字名 (:は含めない, リアクションでローカルホストの場合は@.を付ける (これはdecodeReactionで可能)) - * @param noteUserHost ノートやユーザープロフィールの所有者のホスト - * @returns 絵文字情報, nullは未マッチを意味する - */ -export async function populateEmoji( - emojiName: string, - noteUserHost: string | null, -): Promise<PopulatedEmoji | null> { - const { name, host } = parseEmojiStr(emojiName, noteUserHost); - if (name == null) return null; - - const queryOrNull = async () => - (await Emojis.findOneBy({ - name, - host: host ?? IsNull(), - })) || null; - - const emoji = await cache.fetch(`${name} ${host}`, queryOrNull); - - if (emoji == null) return null; - - const isLocal = emoji.host == null; - const emojiUrl = emoji.publicUrl || emoji.originalUrl; // || emoji.originalUrl してるのは後方互換性のため - const url = isLocal - ? emojiUrl - : `${config.url}/proxy/${encodeURIComponent( - new URL(emojiUrl).pathname, - )}?${query({ url: emojiUrl })}`; - - return { - name: emojiName, - url, - }; -} - -/** - * 複数の添付用絵文字情報を解決する (キャシュ付き, 存在しないものは結果から除外される) - */ -export async function populateEmojis( - emojiNames: string[], - noteUserHost: string | null, -): Promise<PopulatedEmoji[]> { - const emojis = await Promise.all( - emojiNames.map((x) => populateEmoji(x, noteUserHost)), - ); - return emojis.filter((x): x is PopulatedEmoji => x != null); -} - -export function aggregateNoteEmojis(notes: Note[]) { - let emojis: { name: string | null; host: string | null }[] = []; - for (const note of notes) { - emojis = emojis.concat( - note.emojis.map((e) => parseEmojiStr(e, note.userHost)), - ); - if (note.renote) { - emojis = emojis.concat( - note.renote.emojis.map((e) => parseEmojiStr(e, note.renote!.userHost)), - ); - if (note.renote.user) { - emojis = emojis.concat( - note.renote.user.emojis.map((e) => - parseEmojiStr(e, note.renote!.userHost), - ), - ); - } - } - const customReactions = Object.keys(note.reactions) - .map((x) => decodeReaction(x)) - .filter((x) => x.name != null) as typeof emojis; - emojis = emojis.concat(customReactions); - if (note.user) { - emojis = emojis.concat( - note.user.emojis.map((e) => parseEmojiStr(e, note.userHost)), - ); - } - } - return emojis.filter((x) => x.name != null) as { - name: string; - host: string | null; - }[]; -} - -/** - * 与えられた絵文字のリストをデータベースから取得し、キャッシュに追加します - */ -export async function prefetchEmojis( - emojis: { name: string; host: string | null }[], -): Promise<void> { - const notCachedEmojis = emojis.filter( - (emoji) => cache.get(`${emoji.name} ${emoji.host}`) == null, - ); - const emojisQuery: any[] = []; - const hosts = new Set(notCachedEmojis.map((e) => e.host)); - for (const host of hosts) { - emojisQuery.push({ - name: In( - notCachedEmojis.filter((e) => e.host === host).map((e) => e.name), - ), - host: host ?? IsNull(), - }); - } - const _emojis = - emojisQuery.length > 0 - ? await Emojis.find({ - where: emojisQuery, - select: ["name", "host", "originalUrl", "publicUrl"], - }) - : []; - for (const emoji of _emojis) { - cache.set(`${emoji.name} ${emoji.host}`, emoji); - } -} diff --git a/packages/backend/src/misc/post.ts b/packages/backend/src/misc/post.ts deleted file mode 100644 index 90f4f75283..0000000000 --- a/packages/backend/src/misc/post.ts +++ /dev/null @@ -1,19 +0,0 @@ -export type Post = { - text: string | null; - cw: string | null; - localOnly: boolean; - createdAt: Date; -}; - -export function parse(acct: any): Post { - return { - text: acct.text, - cw: acct.cw, - localOnly: acct.localOnly, - createdAt: new Date(acct.createdAt), - }; -} - -export function toJson(acct: Post): string { - return { text: acct.text, cw: acct.cw, localOnly: acct.localOnly }.toString(); -} diff --git a/packages/backend/src/misc/reaction-lib.ts b/packages/backend/src/misc/reaction-lib.ts deleted file mode 100644 index e25b2d6614..0000000000 --- a/packages/backend/src/misc/reaction-lib.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { emojiRegex } from "./emoji-regex.js"; -import { fetchMeta } from "./fetch-meta.js"; -import { Emojis } from "@/models/index.js"; -import { toPunyNullable } from "./convert-host.js"; -import { IsNull } from "typeorm"; - -const legacies = new Map([ - ["like", "👍"], - ["love", "❤️"], - ["laugh", "😆"], - ["hmm", "🤔"], - ["surprise", "😮"], - ["congrats", "🎉"], - ["angry", "💢"], - ["confused", "😥"], - ["rip", "😇"], - ["pudding", "🍮"], - ["star", "⭐"], -]); - -export async function getFallbackReaction() { - const meta = await fetchMeta(); - return meta.defaultReaction; -} - -export function convertLegacyReactions(reactions: Record<string, number>) { - const _reactions = new Map(); - const decodedReactions = new Map(); - - for (const reaction in reactions) { - if (reactions[reaction] <= 0) continue; - - let decodedReaction; - if (decodedReactions.has(reaction)) { - decodedReaction = decodedReactions.get(reaction); - } else { - decodedReaction = decodeReaction(reaction); - decodedReactions.set(reaction, decodedReaction); - } - - let emoji = legacies.get(decodedReaction.reaction); - if (emoji) { - _reactions.set(emoji, (_reactions.get(emoji) || 0) + reactions[reaction]); - } else { - _reactions.set( - reaction, - (_reactions.get(reaction) || 0) + reactions[reaction], - ); - } - } - - const _reactions2 = new Map(); - for (const [reaction, count] of _reactions) { - const decodedReaction = decodedReactions.get(reaction); - _reactions2.set(decodedReaction.reaction, count); - } - - return Object.fromEntries(_reactions2); -} - -export async function toDbReaction( - reaction?: string | null, - reacterHost?: string | null, -): Promise<string> { - if (!reaction) return await getFallbackReaction(); - - reacterHost = toPunyNullable(reacterHost); - - // Convert string-type reactions to unicode - const emoji = legacies.get(reaction) || (reaction === "♥️" ? "❤️" : null); - if (emoji) return emoji; - - // Allow unicode reactions - const match = emojiRegex.exec(reaction); - if (match) { - const unicode = match[0]; - return unicode; - } - - const custom = reaction.match(/^:([\w+-]+)(?:@\.)?:$/); - if (custom) { - const name = custom[1]; - const emoji = await Emojis.findOneBy({ - host: reacterHost || IsNull(), - name, - }); - - if (emoji) return reacterHost ? `:${name}@${reacterHost}:` : `:${name}:`; - } - - return await getFallbackReaction(); -} - -type DecodedReaction = { - /** - * リアクション名 (Unicode Emoji or ':name@hostname' or ':name@.') - */ - reaction: string; - - /** - * name (カスタム絵文字の場合name, Emojiクエリに使う) - */ - name?: string; - - /** - * host (カスタム絵文字の場合host, Emojiクエリに使う) - */ - host?: string | null; -}; - -export function decodeReaction(str: string): DecodedReaction { - const custom = str.match(/^:([\w+-]+)(?:@([\w.-]+))?:$/); - - if (custom) { - const name = custom[1]; - const host = custom[2] || null; - - return { - reaction: `:${name}@${host || "."}:`, // ローカル分は@以降を省略するのではなく.にする - name, - host, - }; - } - - return { - reaction: str, - name: undefined, - host: undefined, - }; -} - -export function convertLegacyReaction(reaction: string): string { - const decoded = decodeReaction(reaction).reaction; - if (legacies.has(decoded)) return legacies.get(decoded)!; - return decoded; -} diff --git a/packages/backend/src/misc/safe-for-sql.ts b/packages/backend/src/misc/safe-for-sql.ts deleted file mode 100644 index 02eb7f0a26..0000000000 --- a/packages/backend/src/misc/safe-for-sql.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function safeForSql(text: string): boolean { - return !/[\0\x08\x09\x1a\n\r"'\\\%]/g.test(text); -} diff --git a/packages/backend/src/misc/schema.ts b/packages/backend/src/misc/schema.ts deleted file mode 100644 index 7eaeb92e04..0000000000 --- a/packages/backend/src/misc/schema.ts +++ /dev/null @@ -1,222 +0,0 @@ -import { - packedUserLiteSchema, - packedUserDetailedNotMeOnlySchema, - packedMeDetailedOnlySchema, - packedUserDetailedNotMeSchema, - packedMeDetailedSchema, - packedUserDetailedSchema, - packedUserSchema, -} from "@/models/schema/user.js"; -import { packedNoteSchema } from "@/models/schema/note.js"; -import { packedUserListSchema } from "@/models/schema/user-list.js"; -import { packedAppSchema } from "@/models/schema/app.js"; -import { packedMessagingMessageSchema } from "@/models/schema/messaging-message.js"; -import { packedNotificationSchema } from "@/models/schema/notification.js"; -import { packedDriveFileSchema } from "@/models/schema/drive-file.js"; -import { packedDriveFolderSchema } from "@/models/schema/drive-folder.js"; -import { packedFollowingSchema } from "@/models/schema/following.js"; -import { packedMutingSchema } from "@/models/schema/muting.js"; -import { packedRenoteMutingSchema } from "@/models/schema/renote-muting.js"; -import { packedBlockingSchema } from "@/models/schema/blocking.js"; -import { packedNoteReactionSchema } from "@/models/schema/note-reaction.js"; -import { packedHashtagSchema } from "@/models/schema/hashtag.js"; -import { packedPageSchema } from "@/models/schema/page.js"; -import { packedUserGroupSchema } from "@/models/schema/user-group.js"; -import { packedNoteFavoriteSchema } from "@/models/schema/note-favorite.js"; -import { packedChannelSchema } from "@/models/schema/channel.js"; -import { packedAntennaSchema } from "@/models/schema/antenna.js"; -import { packedClipSchema } from "@/models/schema/clip.js"; -import { packedFederationInstanceSchema } from "@/models/schema/federation-instance.js"; -import { packedQueueCountSchema } from "@/models/schema/queue.js"; -import { packedGalleryPostSchema } from "@/models/schema/gallery-post.js"; -import { packedEmojiSchema } from "@/models/schema/emoji.js"; - -export const refs = { - UserLite: packedUserLiteSchema, - UserDetailedNotMeOnly: packedUserDetailedNotMeOnlySchema, - MeDetailedOnly: packedMeDetailedOnlySchema, - UserDetailedNotMe: packedUserDetailedNotMeSchema, - MeDetailed: packedMeDetailedSchema, - UserDetailed: packedUserDetailedSchema, - User: packedUserSchema, - - UserList: packedUserListSchema, - UserGroup: packedUserGroupSchema, - App: packedAppSchema, - MessagingMessage: packedMessagingMessageSchema, - Note: packedNoteSchema, - NoteReaction: packedNoteReactionSchema, - NoteFavorite: packedNoteFavoriteSchema, - Notification: packedNotificationSchema, - DriveFile: packedDriveFileSchema, - DriveFolder: packedDriveFolderSchema, - Following: packedFollowingSchema, - Muting: packedMutingSchema, - RenoteMuting: packedRenoteMutingSchema, - Blocking: packedBlockingSchema, - Hashtag: packedHashtagSchema, - Page: packedPageSchema, - Channel: packedChannelSchema, - QueueCount: packedQueueCountSchema, - Antenna: packedAntennaSchema, - Clip: packedClipSchema, - FederationInstance: packedFederationInstanceSchema, - GalleryPost: packedGalleryPostSchema, - Emoji: packedEmojiSchema, -}; - -export type Packed<x extends keyof typeof refs> = SchemaType<typeof refs[x]>; - -type TypeStringef = - | "null" - | "boolean" - | "integer" - | "number" - | "string" - | "array" - | "object" - | "any"; -type StringDefToType<T extends TypeStringef> = T extends "null" - ? null - : T extends "boolean" - ? boolean - : T extends "integer" - ? number - : T extends "number" - ? number - : T extends "string" - ? string | Date - : T extends "array" - ? ReadonlyArray<any> - : T extends "object" - ? Record<string, any> - : any; - -// https://swagger.io/specification/?sbsearch=optional#schema-object -type OfSchema = { - readonly anyOf?: ReadonlyArray<Schema>; - readonly oneOf?: ReadonlyArray<Schema>; - readonly allOf?: ReadonlyArray<Schema>; -}; - -export interface Schema extends OfSchema { - readonly type?: TypeStringef; - readonly nullable?: boolean; - readonly optional?: boolean; - readonly items?: Schema; - readonly properties?: Obj; - readonly required?: ReadonlyArray< - Extract<keyof NonNullable<this["properties"]>, string> - >; - readonly description?: string; - readonly example?: any; - readonly format?: string; - readonly ref?: keyof typeof refs; - readonly enum?: ReadonlyArray<string>; - readonly default?: - | (this["type"] extends TypeStringef ? StringDefToType<this["type"]> : any) - | null; - readonly maxLength?: number; - readonly minLength?: number; - readonly maximum?: number; - readonly minimum?: number; - readonly pattern?: string; -} - -type RequiredPropertyNames<s extends Obj> = { - [K in keyof s]: // K is not optional - s[K]["optional"] extends false - ? K - : // K has default value - s[K]["default"] extends - | null - | string - | number - | boolean - | Record<string, unknown> - ? K - : never; -}[keyof s]; - -export type Obj = Record<string, Schema>; - -// https://github.com/misskey-dev/misskey/issues/8535 -// To avoid excessive stack depth error, -// deceive TypeScript with UnionToIntersection (or more precisely, `infer` expression within it). -export type ObjType< - s extends Obj, - RequiredProps extends keyof s, -> = UnionToIntersection< - { - -readonly [R in RequiredPropertyNames<s>]-?: SchemaType<s[R]>; - } & { - -readonly [R in RequiredProps]-?: SchemaType<s[R]>; - } & { - -readonly [P in keyof s]?: SchemaType<s[P]>; - } ->; - -type NullOrUndefined<p extends Schema, T> = - | (p["nullable"] extends true ? null : never) - | (p["optional"] extends true ? undefined : never) - | T; - -// https://stackoverflow.com/questions/54938141/typescript-convert-union-to-intersection -// Get intersection from union -type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ( - k: infer I, -) => void - ? I - : never; - -// https://github.com/misskey-dev/misskey/pull/8144#discussion_r785287552 -// To get union, we use `Foo extends any ? Hoge<Foo> : never` -type UnionSchemaType< - a extends readonly any[], - X extends Schema = a[number], -> = X extends any ? SchemaType<X> : never; -type ArrayUnion<T> = T extends any ? Array<T> : never; - -export type SchemaTypeDef<p extends Schema> = p["type"] extends "null" - ? null - : p["type"] extends "integer" - ? number - : p["type"] extends "number" - ? number - : p["type"] extends "string" - ? p["enum"] extends readonly string[] - ? p["enum"][number] - : p["format"] extends "date-time" - ? string - : // Dateにする?? - string - : p["type"] extends "boolean" - ? boolean - : p["type"] extends "object" - ? p["ref"] extends keyof typeof refs - ? Packed<p["ref"]> - : p["properties"] extends NonNullable<Obj> - ? ObjType<p["properties"], NonNullable<p["required"]>[number]> - : p["anyOf"] extends ReadonlyArray<Schema> - ? UnionSchemaType<p["anyOf"]> & - Partial<UnionToIntersection<UnionSchemaType<p["anyOf"]>>> - : p["allOf"] extends ReadonlyArray<Schema> - ? UnionToIntersection<UnionSchemaType<p["allOf"]>> - : any - : p["type"] extends "array" - ? p["items"] extends OfSchema - ? p["items"]["anyOf"] extends ReadonlyArray<Schema> - ? UnionSchemaType<NonNullable<p["items"]["anyOf"]>>[] - : p["items"]["oneOf"] extends ReadonlyArray<Schema> - ? ArrayUnion<UnionSchemaType<NonNullable<p["items"]["oneOf"]>>> - : p["items"]["allOf"] extends ReadonlyArray<Schema> - ? UnionToIntersection<UnionSchemaType<NonNullable<p["items"]["allOf"]>>>[] - : never - : p["items"] extends NonNullable<Schema> - ? SchemaTypeDef<p["items"]>[] - : any[] - : p["oneOf"] extends ReadonlyArray<Schema> - ? UnionSchemaType<p["oneOf"]> - : any; - -export type SchemaType<p extends Schema> = NullOrUndefined<p, SchemaTypeDef<p>>; diff --git a/packages/backend/src/misc/secure-rndstr.ts b/packages/backend/src/misc/secure-rndstr.ts deleted file mode 100644 index 7f5754e1c5..0000000000 --- a/packages/backend/src/misc/secure-rndstr.ts +++ /dev/null @@ -1,24 +0,0 @@ -import * as crypto from "node:crypto"; - -const L_CHARS = "0123456789abcdefghijklmnopqrstuvwxyz"; -const LU_CHARS = - "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - -export function secureRndstr(length = 32, useLU = true): string { - const chars = useLU ? LU_CHARS : L_CHARS; - const chars_len = chars.length; - - let str = ""; - - for (let i = 0; i < length; i++) { - let rand = Math.floor( - (crypto.randomBytes(1).readUInt8(0) / 0xff) * chars_len, - ); - if (rand === chars_len) { - rand = chars_len - 1; - } - str += chars.charAt(rand); - } - - return str; -} diff --git a/packages/backend/src/misc/should-block-instance.ts b/packages/backend/src/misc/should-block-instance.ts deleted file mode 100644 index 6e46232428..0000000000 --- a/packages/backend/src/misc/should-block-instance.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { fetchMeta } from "@/misc/fetch-meta.js"; -import type { Instance } from "@/models/entities/instance.js"; -import type { Meta } from "@/models/entities/meta.js"; - -/** - * Returns whether a specific host (punycoded) should be blocked. - * - * @param host punycoded instance host - * @param meta a resolved Meta table - * @returns whether the given host should be blocked - */ -export async function shouldBlockInstance( - host: Instance["host"], - meta?: Meta, -): Promise<boolean> { - const { blockedHosts } = meta ?? (await fetchMeta()); - return blockedHosts.some( - (blockedHost) => host === blockedHost || host.endsWith(`.${blockedHost}`), - ); -} diff --git a/packages/backend/src/misc/show-machine-info.ts b/packages/backend/src/misc/show-machine-info.ts deleted file mode 100644 index d3a28cbd37..0000000000 --- a/packages/backend/src/misc/show-machine-info.ts +++ /dev/null @@ -1,17 +0,0 @@ -import * as os from "node:os"; -import sysUtils from "systeminformation"; -import type Logger from "@/services/logger.js"; - -export async function showMachineInfo(parentLogger: Logger) { - const logger = parentLogger.createSubLogger("machine"); - logger.debug(`Hostname: ${os.hostname()}`); - logger.debug(`Platform: ${process.platform} Arch: ${process.arch}`); - const mem = await sysUtils.mem(); - const totalmem = (mem.total / 1024 / 1024 / 1024).toFixed(1); - const availmem = (mem.available / 1024 / 1024 / 1024).toFixed(1); - logger.debug( - `CPU: ${ - os.cpus().length - } core MEM: ${totalmem}GB (available: ${availmem}GB)`, - ); -} diff --git a/packages/backend/src/misc/skipped-instances.ts b/packages/backend/src/misc/skipped-instances.ts deleted file mode 100644 index 785393022a..0000000000 --- a/packages/backend/src/misc/skipped-instances.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { Brackets } from "typeorm"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { Instances } from "@/models/index.js"; -import type { Instance } from "@/models/entities/instance.js"; -import { DAY } from "@/const.js"; -import { shouldBlockInstance } from "./should-block-instance.js"; - -// Threshold from last contact after which an instance will be considered -// "dead" and should no longer get activities delivered to it. -const deadThreshold = 7 * DAY; - -/** - * Returns the subset of hosts which should be skipped. - * - * @param hosts array of punycoded instance hosts - * @returns array of punycoed instance hosts that should be skipped (subset of hosts parameter) - */ -export async function skippedInstances( - hosts: Instance["host"][], -): Promise<Instance["host"][]> { - // first check for blocked instances since that info may already be in memory - const meta = await fetchMeta(); - const shouldSkip = await Promise.all( - hosts.map((host) => shouldBlockInstance(host, meta)), - ); - const skipped = hosts.filter((_, i) => shouldSkip[i]); - - // if possible return early and skip accessing the database - if (skipped.length === hosts.length) return hosts; - - const deadTime = new Date(Date.now() - deadThreshold); - - return skipped.concat( - await Instances.createQueryBuilder("instance") - .where("instance.host in (:...hosts)", { - // don't check hosts again that we already know are suspended - // also avoids adding duplicates to the list - hosts: hosts.filter((host) => !skipped.includes(host)), - }) - .andWhere( - new Brackets((qb) => { - qb.where("instance.isSuspended"); - }), - ) - .select("host") - .getRawMany(), - ); -} - -/** - * Returns whether a specific host (punycoded) should be skipped. - * Convenience wrapper around skippedInstances which should only be used if there is a single host to check. - * If you have multiple hosts, consider using skippedInstances instead to do a bulk check. - * - * @param host punycoded instance host - * @returns whether the given host should be skipped - */ -export async function shouldSkipInstance( - host: Instance["host"], -): Promise<boolean> { - const skipped = await skippedInstances([host]); - return skipped.length > 0; -} diff --git a/packages/backend/src/misc/truncate.ts b/packages/backend/src/misc/truncate.ts deleted file mode 100644 index 6bc58941a2..0000000000 --- a/packages/backend/src/misc/truncate.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { substring } from "stringz"; - -export function truncate(input: string, size: number): string; -export function truncate( - input: string | undefined, - size: number, -): string | undefined; -export function truncate( - input: string | undefined, - size: number, -): string | undefined { - if (!input) { - return input; - } else { - return substring(input, 0, size); - } -} diff --git a/packages/backend/src/misc/webhook-cache.ts b/packages/backend/src/misc/webhook-cache.ts deleted file mode 100644 index 1eda5eaecd..0000000000 --- a/packages/backend/src/misc/webhook-cache.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { Webhooks } from "@/models/index.js"; -import type { Webhook } from "@/models/entities/webhook.js"; -import { subscriber } from "@/db/redis.js"; - -let webhooksFetched = false; -let webhooks: Webhook[] = []; - -export async function getActiveWebhooks() { - if (!webhooksFetched) { - webhooks = await Webhooks.findBy({ - active: true, - }); - webhooksFetched = true; - } - - return webhooks; -} - -subscriber.on("message", async (_, data) => { - const obj = JSON.parse(data); - - if (obj.channel === "internal") { - const { type, body } = obj.message; - switch (type) { - case "webhookCreated": - if (body.active) { - webhooks.push(body); - } - break; - case "webhookUpdated": - if (body.active) { - const i = webhooks.findIndex((a) => a.id === body.id); - if (i > -1) { - webhooks[i] = body; - } else { - webhooks.push(body); - } - } else { - webhooks = webhooks.filter((a) => a.id !== body.id); - } - break; - case "webhookDeleted": - webhooks = webhooks.filter((a) => a.id !== body.id); - break; - default: - break; - } - } -}); diff --git a/packages/backend/src/models/entities/abuse-user-report.ts b/packages/backend/src/models/entities/abuse-user-report.ts deleted file mode 100644 index 655fdd3ca6..0000000000 --- a/packages/backend/src/models/entities/abuse-user-report.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -export class AbuseUserReport { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the AbuseUserReport.', - }) - public createdAt: Date; - - @Index() - @Column(id()) - public targetUserId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public targetUser: User | null; - - @Index() - @Column(id()) - public reporterId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public reporter: User | null; - - @Column({ - ...id(), - nullable: true, - }) - public assigneeId: User["id"] | null; - - @ManyToOne(type => User, { - onDelete: 'SET NULL', - }) - @JoinColumn() - public assignee: User | null; - - @Index() - @Column('boolean', { - default: false, - }) - public resolved: boolean; - - @Column('boolean', { - default: false - }) - public forwarded: boolean; - - @Column('varchar', { - length: 2048, - }) - public comment: string; - - //#region Denormalized fields - @Index() - @Column('varchar', { - length: 128, nullable: true, - comment: '[Denormalized]', - }) - public targetUserHost: string | null; - - @Index() - @Column('varchar', { - length: 128, nullable: true, - comment: '[Denormalized]', - }) - public reporterHost: string | null; - //#endregion -} diff --git a/packages/backend/src/models/entities/access-token.ts b/packages/backend/src/models/entities/access-token.ts deleted file mode 100644 index 83d7bbda86..0000000000 --- a/packages/backend/src/models/entities/access-token.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { - Entity, - PrimaryColumn, - Index, - Column, - ManyToOne, - JoinColumn, -} from "typeorm"; -import { User } from "./user.js"; -import { App } from "./app.js"; -import { id } from "../id.js"; - -@Entity() -export class AccessToken { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the AccessToken.', - }) - public createdAt: Date; - - @Column('timestamp with time zone', { - nullable: true, - }) - public lastUsedAt: Date | null; - - @Index() - @Column('varchar', { - length: 128, - }) - public token: string; - - @Index() - @Column('varchar', { - length: 128, - nullable: true, - }) - public session: string | null; - - @Index() - @Column('varchar', { - length: 128, - }) - public hash: string; - - @Index() - @Column(id()) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column({ - ...id(), - nullable: true, - }) - public appId: App["id"] | null; - - @ManyToOne(type => App, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public app: App | null; - - @Column('varchar', { - length: 128, - nullable: true, - }) - public name: string | null; - - @Column('varchar', { - length: 512, - nullable: true, - }) - public description: string | null; - - @Column('varchar', { - length: 512, - nullable: true, - }) - public iconUrl: string | null; - - @Column('varchar', { - length: 64, array: true, - default: '{}', - }) - public permission: string[]; - - @Column('boolean', { - default: false, - }) - public fetched: boolean; -} diff --git a/packages/backend/src/models/entities/ad.ts b/packages/backend/src/models/entities/ad.ts deleted file mode 100644 index fa42973652..0000000000 --- a/packages/backend/src/models/entities/ad.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { Entity, Index, Column, PrimaryColumn } from "typeorm"; -import { id } from "../id.js"; - -@Entity() -export class Ad { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the Ad.', - }) - public createdAt: Date; - - @Index() - @Column('timestamp with time zone', { - comment: 'The expired date of the Ad.', - }) - public expiresAt: Date; - - @Column('varchar', { - length: 32, nullable: false, - }) - public place: string; - - // 今は使われていないが将来的に活用される可能性はある - @Column('varchar', { - length: 32, nullable: false, - }) - public priority: string; - - @Column('integer', { - default: 1, nullable: false, - }) - public ratio: number; - - @Column('varchar', { - length: 1024, nullable: false, - }) - public url: string; - - @Column('varchar', { - length: 1024, nullable: false, - }) - public imageUrl: string; - - @Column('varchar', { - length: 8192, nullable: false, - }) - public memo: string; - - constructor(data: Partial<Ad>) { - if (data == null) return; - - for (const [k, v] of Object.entries(data)) { - (this as any)[k] = v; - } - } -} diff --git a/packages/backend/src/models/entities/announcement-read.ts b/packages/backend/src/models/entities/announcement-read.ts deleted file mode 100644 index 87d0f0e9ed..0000000000 --- a/packages/backend/src/models/entities/announcement-read.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { Announcement } from "./announcement.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['userId', 'announcementId'], { unique: true }) -export class AnnouncementRead { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the AnnouncementRead.', - }) - public createdAt: Date; - - @Index() - @Column(id()) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Index() - @Column(id()) - public announcementId: Announcement["id"]; - - @ManyToOne(type => Announcement, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public announcement: Announcement | null; -} diff --git a/packages/backend/src/models/entities/announcement.ts b/packages/backend/src/models/entities/announcement.ts deleted file mode 100644 index 9d45af0149..0000000000 --- a/packages/backend/src/models/entities/announcement.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { Entity, Index, Column, PrimaryColumn } from "typeorm"; -import { id } from "../id.js"; - -@Entity() -export class Announcement { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the Announcement.', - }) - public createdAt: Date; - - @Column('timestamp with time zone', { - comment: 'The updated date of the Announcement.', - nullable: true, - }) - public updatedAt: Date | null; - - @Column('varchar', { - length: 8192, nullable: false, - }) - public text: string; - - @Column('varchar', { - length: 256, nullable: false, - }) - public title: string; - - @Column('varchar', { - length: 1024, nullable: true, - }) - public imageUrl: string | null; - - constructor(data: Partial<Announcement>) { - if (data == null) return; - - for (const [k, v] of Object.entries(data)) { - (this as any)[k] = v; - } - } -} diff --git a/packages/backend/src/models/entities/antenna-note.ts b/packages/backend/src/models/entities/antenna-note.ts deleted file mode 100644 index c47c796bbf..0000000000 --- a/packages/backend/src/models/entities/antenna-note.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { - Entity, - Index, - JoinColumn, - Column, - ManyToOne, - PrimaryColumn, -} from "typeorm"; -import { Note } from "./note.js"; -import { Antenna } from "./antenna.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['noteId', 'antennaId'], { unique: true }) -export class AntennaNote { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column({ - ...id(), - comment: 'The note ID.', - }) - public noteId: Note["id"]; - - @ManyToOne(type => Note, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public note: Note | null; - - @Index() - @Column({ - ...id(), - comment: 'The antenna ID.', - }) - public antennaId: Antenna["id"]; - - @ManyToOne(type => Antenna, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public antenna: Antenna | null; - - @Index() - @Column('boolean', { - default: false, - }) - public read: boolean; -} diff --git a/packages/backend/src/models/entities/antenna.ts b/packages/backend/src/models/entities/antenna.ts deleted file mode 100644 index c653b2a051..0000000000 --- a/packages/backend/src/models/entities/antenna.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; -import { UserList } from "./user-list.js"; -import { UserGroupJoining } from "./user-group-joining.js"; - -@Entity() -export class Antenna { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the Antenna.', - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - comment: 'The owner ID.', - }) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column('varchar', { - length: 128, - comment: 'The name of the Antenna.', - }) - public name: string; - - @Column('enum', { enum: ['home', 'all', 'users', 'list', 'group', 'instances'] }) - public src: "home" | "all" | "users" | "list" | "group" | "instances"; - - @Column({ - ...id(), - nullable: true, - }) - public userListId: UserList["id"] | null; - - @ManyToOne(type => UserList, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public userList: UserList | null; - - @Column({ - ...id(), - nullable: true, - }) - public userGroupJoiningId: UserGroupJoining["id"] | null; - - @ManyToOne(type => UserGroupJoining, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public userGroupJoining: UserGroupJoining | null; - - @Column('varchar', { - length: 1024, array: true, - default: '{}', - }) - public users: string[]; - - @Column('jsonb', { - default: [], - }) - public instances: string[]; - - @Column('jsonb', { - default: [], - }) - public keywords: string[][]; - - @Column('jsonb', { - default: [], - }) - public excludeKeywords: string[][]; - - @Column('boolean', { - default: false, - }) - public caseSensitive: boolean; - - @Column('boolean', { - default: false, - }) - public withReplies: boolean; - - @Column('boolean') - public withFile: boolean; - - @Column('varchar', { - length: 2048, nullable: true, - }) - public expression: string | null; - - @Column('boolean') - public notify: boolean; -} diff --git a/packages/backend/src/models/entities/app.ts b/packages/backend/src/models/entities/app.ts deleted file mode 100644 index bb33eede4f..0000000000 --- a/packages/backend/src/models/entities/app.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { Entity, PrimaryColumn, Column, Index, ManyToOne } from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -export class App { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the App.', - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - nullable: true, - comment: 'The owner ID.', - }) - public userId: User["id"] | null; - - @ManyToOne(type => User, { - onDelete: 'SET NULL', - nullable: true, - }) - public user: User | null; - - @Index() - @Column('varchar', { - length: 64, - comment: 'The secret key of the App.', - }) - public secret: string; - - @Column('varchar', { - length: 128, - comment: 'The name of the App.', - }) - public name: string; - - @Column('varchar', { - length: 512, - comment: 'The description of the App.', - }) - public description: string; - - @Column('varchar', { - length: 64, array: true, - comment: 'The permission of the App.', - }) - public permission: string[]; - - @Column('varchar', { - length: 512, nullable: true, - comment: 'The callbackUrl of the App.', - }) - public callbackUrl: string | null; -} diff --git a/packages/backend/src/models/entities/attestation-challenge.ts b/packages/backend/src/models/entities/attestation-challenge.ts deleted file mode 100644 index 7a87d42be0..0000000000 --- a/packages/backend/src/models/entities/attestation-challenge.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { - PrimaryColumn, - Entity, - JoinColumn, - Column, - ManyToOne, - Index, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -export class AttestationChallenge { - @PrimaryColumn(id()) - public id: string; - - @Index() - @PrimaryColumn(id()) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Index() - @Column('varchar', { - length: 64, - comment: 'Hex-encoded sha256 hash of the challenge.', - }) - public challenge: string; - - @Column('timestamp with time zone', { - comment: 'The date challenge was created for expiry purposes.', - }) - public createdAt: Date; - - @Column('boolean', { - comment: - 'Indicates that the challenge is only for registration purposes if true to prevent the challenge for being used as authentication.', - default: false, - }) - public registrationChallenge: boolean; - - constructor(data: Partial<AttestationChallenge>) { - if (data == null) return; - - for (const [k, v] of Object.entries(data)) { - (this as any)[k] = v; - } - } -} diff --git a/packages/backend/src/models/entities/auth-session.ts b/packages/backend/src/models/entities/auth-session.ts deleted file mode 100644 index b762f84625..0000000000 --- a/packages/backend/src/models/entities/auth-session.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { - Entity, - PrimaryColumn, - Index, - Column, - ManyToOne, - JoinColumn, -} from "typeorm"; -import { User } from "./user.js"; -import { App } from "./app.js"; -import { id } from "../id.js"; - -@Entity() -export class AuthSession { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the AuthSession.', - }) - public createdAt: Date; - - @Index() - @Column('varchar', { - length: 128, - }) - public token: string; - - @Column({ - ...id(), - nullable: true, - }) - public userId: User["id"] | null; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - nullable: true, - }) - @JoinColumn() - public user: User | null; - - @Column(id()) - public appId: App["id"]; - - @ManyToOne(type => App, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public app: App | null; -} diff --git a/packages/backend/src/models/entities/blocking.ts b/packages/backend/src/models/entities/blocking.ts deleted file mode 100644 index 3a44a4d656..0000000000 --- a/packages/backend/src/models/entities/blocking.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['blockerId', 'blockeeId'], { unique: true }) -export class Blocking { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the Blocking.', - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - comment: 'The blockee user ID.', - }) - public blockeeId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public blockee: User | null; - - @Index() - @Column({ - ...id(), - comment: 'The blocker user ID.', - }) - public blockerId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public blocker: User | null; -} diff --git a/packages/backend/src/models/entities/channel-following.ts b/packages/backend/src/models/entities/channel-following.ts deleted file mode 100644 index 04ec193e19..0000000000 --- a/packages/backend/src/models/entities/channel-following.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; -import { Channel } from "./channel.js"; - -@Entity() -@Index(['followerId', 'followeeId'], { unique: true }) -export class ChannelFollowing { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the ChannelFollowing.', - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - comment: 'The followee channel ID.', - }) - public followeeId: Channel["id"]; - - @ManyToOne(type => Channel, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public followee: Channel | null; - - @Index() - @Column({ - ...id(), - comment: 'The follower user ID.', - }) - public followerId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public follower: User | null; -} diff --git a/packages/backend/src/models/entities/channel-note-pining.ts b/packages/backend/src/models/entities/channel-note-pining.ts deleted file mode 100644 index bd13f4ca39..0000000000 --- a/packages/backend/src/models/entities/channel-note-pining.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { Note } from "./note.js"; -import { Channel } from "./channel.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['channelId', 'noteId'], { unique: true }) -export class ChannelNotePining { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the ChannelNotePining.', - }) - public createdAt: Date; - - @Index() - @Column(id()) - public channelId: Channel["id"]; - - @ManyToOne(type => Channel, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public channel: Channel | null; - - @Column(id()) - public noteId: Note["id"]; - - @ManyToOne(type => Note, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public note: Note | null; -} diff --git a/packages/backend/src/models/entities/channel.ts b/packages/backend/src/models/entities/channel.ts deleted file mode 100644 index 7f9851dbf9..0000000000 --- a/packages/backend/src/models/entities/channel.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; -import { DriveFile } from "./drive-file.js"; - -@Entity() -export class Channel { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the Channel.', - }) - public createdAt: Date; - - @Index() - @Column('timestamp with time zone', { - nullable: true, - }) - public lastNotedAt: Date | null; - - @Index() - @Column({ - ...id(), - nullable: true, - comment: 'The owner ID.', - }) - public userId: User["id"] | null; - - @ManyToOne(type => User, { - onDelete: 'SET NULL', - }) - @JoinColumn() - public user: User | null; - - @Column('varchar', { - length: 128, - comment: 'The name of the Channel.', - }) - public name: string; - - @Column('varchar', { - length: 2048, nullable: true, - comment: 'The description of the Channel.', - }) - public description: string | null; - - @Column({ - ...id(), - nullable: true, - comment: 'The ID of banner Channel.', - }) - public bannerId: DriveFile["id"] | null; - - @ManyToOne(type => DriveFile, { - onDelete: 'SET NULL', - }) - @JoinColumn() - public banner: DriveFile | null; - - @Index() - @Column('integer', { - default: 0, - comment: 'The count of notes.', - }) - public notesCount: number; - - @Index() - @Column('integer', { - default: 0, - comment: 'The count of users.', - }) - public usersCount: number; -} diff --git a/packages/backend/src/models/entities/clip-note.ts b/packages/backend/src/models/entities/clip-note.ts deleted file mode 100644 index bc51daaf4d..0000000000 --- a/packages/backend/src/models/entities/clip-note.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { - Entity, - Index, - JoinColumn, - Column, - ManyToOne, - PrimaryColumn, -} from "typeorm"; -import { Note } from "./note.js"; -import { Clip } from "./clip.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['noteId', 'clipId'], { unique: true }) -export class ClipNote { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column({ - ...id(), - comment: 'The note ID.', - }) - public noteId: Note["id"]; - - @ManyToOne(type => Note, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public note: Note | null; - - @Index() - @Column({ - ...id(), - comment: 'The clip ID.', - }) - public clipId: Clip["id"]; - - @ManyToOne(type => Clip, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public clip: Clip | null; -} diff --git a/packages/backend/src/models/entities/clip.ts b/packages/backend/src/models/entities/clip.ts deleted file mode 100644 index 10591cbeef..0000000000 --- a/packages/backend/src/models/entities/clip.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -export class Clip { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the Clip.', - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - comment: 'The owner ID.', - }) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column('varchar', { - length: 128, - comment: 'The name of the Clip.', - }) - public name: string; - - @Column('boolean', { - default: false, - }) - public isPublic: boolean; - - @Column('varchar', { - length: 2048, nullable: true, - comment: 'The description of the Clip.', - }) - public description: string | null; -} diff --git a/packages/backend/src/models/entities/drive-file.ts b/packages/backend/src/models/entities/drive-file.ts deleted file mode 100644 index 32e19bc6ee..0000000000 --- a/packages/backend/src/models/entities/drive-file.ts +++ /dev/null @@ -1,206 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { id } from "../id.js"; -import { User } from "./user.js"; -import { DriveFolder } from "./drive-folder.js"; -import { DB_MAX_IMAGE_COMMENT_LENGTH } from "@/misc/hard-limits.js"; - -@Entity() -@Index(['userId', 'folderId', 'id']) -export class DriveFile { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the DriveFile.', - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - nullable: true, - comment: 'The owner ID.', - }) - public userId: User["id"] | null; - - @ManyToOne(type => User, { - onDelete: 'SET NULL', - }) - @JoinColumn() - public user: User | null; - - @Index() - @Column('varchar', { - length: 128, nullable: true, - comment: 'The host of owner. It will be null if the user in local.', - }) - public userHost: string | null; - - @Index() - @Column('varchar', { - length: 32, - comment: 'The MD5 hash of the DriveFile.', - }) - public md5: string; - - @Column('varchar', { - length: 256, - comment: 'The file name of the DriveFile.', - }) - public name: string; - - @Index() - @Column('varchar', { - length: 128, - comment: 'The content type (MIME) of the DriveFile.', - }) - public type: string; - - @Column('integer', { - comment: 'The file size (bytes) of the DriveFile.', - }) - public size: number; - - @Column('varchar', { - length: DB_MAX_IMAGE_COMMENT_LENGTH, - nullable: true, - comment: 'The comment of the DriveFile.', - }) - public comment: string | null; - - @Column('varchar', { - length: 128, nullable: true, - comment: 'The BlurHash string.', - }) - public blurhash: string | null; - - @Column('jsonb', { - default: {}, - comment: 'The any properties of the DriveFile. For example, it includes image width/height.', - }) - public properties: { - width?: number; - height?: number; - orientation?: number; - avgColor?: string; - }; - - @Column('boolean') - public storedInternal: boolean; - - @Column('varchar', { - length: 512, - comment: 'The URL of the DriveFile.', - }) - public url: string; - - @Column('varchar', { - length: 512, nullable: true, - comment: 'The URL of the thumbnail of the DriveFile.', - }) - public thumbnailUrl: string | null; - - @Column('varchar', { - length: 512, nullable: true, - comment: 'The URL of the webpublic of the DriveFile.', - }) - public webpublicUrl: string | null; - - @Column('varchar', { - length: 128, nullable: true, - }) - public webpublicType: string | null; - - @Index({ unique: true }) - @Column('varchar', { - length: 256, nullable: true, - }) - public accessKey: string | null; - - @Index({ unique: true }) - @Column('varchar', { - length: 256, nullable: true, - }) - public thumbnailAccessKey: string | null; - - @Index({ unique: true }) - @Column('varchar', { - length: 256, nullable: true, - }) - public webpublicAccessKey: string | null; - - @Index() - @Column('varchar', { - length: 512, nullable: true, - comment: 'The URI of the DriveFile. it will be null when the DriveFile is local.', - }) - public uri: string | null; - - @Column('varchar', { - length: 512, nullable: true, - }) - public src: string | null; - - @Index() - @Column({ - ...id(), - nullable: true, - comment: 'The parent folder ID. If null, it means the DriveFile is located in root.', - }) - public folderId: DriveFolder["id"] | null; - - @ManyToOne(type => DriveFolder, { - onDelete: 'SET NULL', - }) - @JoinColumn() - public folder: DriveFolder | null; - - @Index() - @Column('boolean', { - default: false, - comment: 'Whether the DriveFile is NSFW.', - }) - public isSensitive: boolean; - - @Index() - @Column('boolean', { - default: false, - comment: 'Whether the DriveFile is NSFW. (predict)', - }) - public maybeSensitive: boolean; - - @Index() - @Column('boolean', { - default: false, - }) - public maybePorn: boolean; - - /** - * 外部の(信頼されていない)URLへの直リンクか否か - */ - @Index() - @Column('boolean', { - default: false, - comment: 'Whether the DriveFile is direct link to remote server.', - }) - public isLink: boolean; - - @Column('jsonb', { - default: {}, - nullable: true, - }) - public requestHeaders: Record<string, string> | null; - - @Column('varchar', { - length: 128, nullable: true, - }) - public requestIp: string | null; -} diff --git a/packages/backend/src/models/entities/drive-folder.ts b/packages/backend/src/models/entities/drive-folder.ts deleted file mode 100644 index 77031ce4ea..0000000000 --- a/packages/backend/src/models/entities/drive-folder.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { - JoinColumn, - ManyToOne, - Entity, - PrimaryColumn, - Index, - Column, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -export class DriveFolder { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the DriveFolder.', - }) - public createdAt: Date; - - @Column('varchar', { - length: 128, - comment: 'The name of the DriveFolder.', - }) - public name: string; - - @Index() - @Column({ - ...id(), - nullable: true, - comment: 'The owner ID.', - }) - public userId: User["id"] | null; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Index() - @Column({ - ...id(), - nullable: true, - comment: 'The parent folder ID. If null, it means the DriveFolder is located in root.', - }) - public parentId: DriveFolder["id"] | null; - - @ManyToOne(type => DriveFolder, { - onDelete: 'SET NULL', - }) - @JoinColumn() - public parent: DriveFolder | null; -} diff --git a/packages/backend/src/models/entities/emoji.ts b/packages/backend/src/models/entities/emoji.ts deleted file mode 100644 index 2315686968..0000000000 --- a/packages/backend/src/models/entities/emoji.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { PrimaryColumn, Entity, Index, Column } from "typeorm"; -import { id } from "../id.js"; - -@Entity() -@Index(['name', 'host'], { unique: true }) -export class Emoji { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - nullable: true, - }) - public updatedAt: Date | null; - - @Index() - @Column('varchar', { - length: 128, - }) - public name: string; - - @Index() - @Column('varchar', { - length: 128, nullable: true, - }) - public host: string | null; - - @Column('varchar', { - length: 128, nullable: true, - }) - public category: string | null; - - @Column('varchar', { - length: 512, - }) - public originalUrl: string; - - @Column('varchar', { - length: 512, - default: '', - }) - public publicUrl: string; - - @Column('varchar', { - length: 512, nullable: true, - }) - public uri: string | null; - - // publicUrlの方のtypeが入る - @Column('varchar', { - length: 64, nullable: true, - }) - public type: string | null; - - @Column('varchar', { - array: true, length: 128, default: '{}', - }) - public aliases: string[]; - - @Column('varchar', { - length: 1024, nullable: true, - }) - public license: string | null; -} diff --git a/packages/backend/src/models/entities/follow-request.ts b/packages/backend/src/models/entities/follow-request.ts deleted file mode 100644 index 658fed5a5e..0000000000 --- a/packages/backend/src/models/entities/follow-request.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['followerId', 'followeeId'], { unique: true }) -export class FollowRequest { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the FollowRequest.', - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - comment: 'The followee user ID.', - }) - public followeeId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public followee: User | null; - - @Index() - @Column({ - ...id(), - comment: 'The follower user ID.', - }) - public followerId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public follower: User | null; - - @Column('varchar', { - length: 128, nullable: true, - comment: 'id of Follow Activity.', - }) - public requestId: string | null; - - //#region Denormalized fields - @Column('varchar', { - length: 128, nullable: true, - comment: '[Denormalized]', - }) - public followerHost: string | null; - - @Column('varchar', { - length: 512, nullable: true, - comment: '[Denormalized]', - }) - public followerInbox: string | null; - - @Column('varchar', { - length: 512, nullable: true, - comment: '[Denormalized]', - }) - public followerSharedInbox: string | null; - - @Column('varchar', { - length: 128, nullable: true, - comment: '[Denormalized]', - }) - public followeeHost: string | null; - - @Column('varchar', { - length: 512, nullable: true, - comment: '[Denormalized]', - }) - public followeeInbox: string | null; - - @Column('varchar', { - length: 512, nullable: true, - comment: '[Denormalized]', - }) - public followeeSharedInbox: string | null; - //#endregion -} diff --git a/packages/backend/src/models/entities/following.ts b/packages/backend/src/models/entities/following.ts deleted file mode 100644 index 11f633fcd8..0000000000 --- a/packages/backend/src/models/entities/following.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['followerId', 'followeeId'], { unique: true }) -export class Following { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the Following.', - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - comment: 'The followee user ID.', - }) - public followeeId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public followee: User | null; - - @Index() - @Column({ - ...id(), - comment: 'The follower user ID.', - }) - public followerId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public follower: User | null; - - //#region Denormalized fields - @Index() - @Column('varchar', { - length: 128, nullable: true, - comment: '[Denormalized]', - }) - public followerHost: string | null; - - @Column('varchar', { - length: 512, nullable: true, - comment: '[Denormalized]', - }) - public followerInbox: string | null; - - @Column('varchar', { - length: 512, nullable: true, - comment: '[Denormalized]', - }) - public followerSharedInbox: string | null; - - @Index() - @Column('varchar', { - length: 128, nullable: true, - comment: '[Denormalized]', - }) - public followeeHost: string | null; - - @Column('varchar', { - length: 512, nullable: true, - comment: '[Denormalized]', - }) - public followeeInbox: string | null; - - @Column('varchar', { - length: 512, nullable: true, - comment: '[Denormalized]', - }) - public followeeSharedInbox: string | null; - //#endregion -} diff --git a/packages/backend/src/models/entities/gallery-like.ts b/packages/backend/src/models/entities/gallery-like.ts deleted file mode 100644 index e74e3c3ce5..0000000000 --- a/packages/backend/src/models/entities/gallery-like.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; -import { GalleryPost } from "./gallery-post.js"; - -@Entity() -@Index(['userId', 'postId'], { unique: true }) -export class GalleryLike { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone') - public createdAt: Date; - - @Index() - @Column(id()) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column(id()) - public postId: GalleryPost["id"]; - - @ManyToOne(type => GalleryPost, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public post: GalleryPost | null; -} diff --git a/packages/backend/src/models/entities/gallery-post.ts b/packages/backend/src/models/entities/gallery-post.ts deleted file mode 100644 index a79bb88353..0000000000 --- a/packages/backend/src/models/entities/gallery-post.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { - Entity, - Index, - JoinColumn, - Column, - PrimaryColumn, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; -import type { DriveFile } from "./drive-file.js"; - -@Entity() -export class GalleryPost { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the GalleryPost.', - }) - public createdAt: Date; - - @Index() - @Column('timestamp with time zone', { - comment: 'The updated date of the GalleryPost.', - }) - public updatedAt: Date; - - @Column('varchar', { - length: 256, - }) - public title: string; - - @Column('varchar', { - length: 2048, nullable: true, - }) - public description: string | null; - - @Index() - @Column({ - ...id(), - comment: 'The ID of author.', - }) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Index() - @Column({ - ...id(), - array: true, default: '{}', - }) - public fileIds: DriveFile["id"][]; - - @Index() - @Column('boolean', { - default: false, - comment: 'Whether the post is sensitive.', - }) - public isSensitive: boolean; - - @Index() - @Column('integer', { - default: 0, - }) - public likedCount: number; - - @Index() - @Column('varchar', { - length: 128, array: true, default: '{}', - }) - public tags: string[]; - - constructor(data: Partial<GalleryPost>) { - if (data == null) return; - - for (const [k, v] of Object.entries(data)) { - (this as any)[k] = v; - } - } -} diff --git a/packages/backend/src/models/entities/hashtag.ts b/packages/backend/src/models/entities/hashtag.ts deleted file mode 100644 index 06fa004be4..0000000000 --- a/packages/backend/src/models/entities/hashtag.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { Entity, PrimaryColumn, Index, Column } from "typeorm"; -import type { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -export class Hashtag { - @PrimaryColumn(id()) - public id: string; - - @Index({ unique: true }) - @Column('varchar', { - length: 128, - }) - public name: string; - - @Column({ - ...id(), - array: true, - }) - public mentionedUserIds: User["id"][]; - - @Index() - @Column('integer', { - default: 0, - }) - public mentionedUsersCount: number; - - @Column({ - ...id(), - array: true, - }) - public mentionedLocalUserIds: User["id"][]; - - @Index() - @Column('integer', { - default: 0, - }) - public mentionedLocalUsersCount: number; - - @Column({ - ...id(), - array: true, - }) - public mentionedRemoteUserIds: User["id"][]; - - @Index() - @Column('integer', { - default: 0, - }) - public mentionedRemoteUsersCount: number; - - @Column({ - ...id(), - array: true, - }) - public attachedUserIds: User["id"][]; - - @Index() - @Column('integer', { - default: 0, - }) - public attachedUsersCount: number; - - @Column({ - ...id(), - array: true, - }) - public attachedLocalUserIds: User["id"][]; - - @Index() - @Column('integer', { - default: 0, - }) - public attachedLocalUsersCount: number; - - @Column({ - ...id(), - array: true, - }) - public attachedRemoteUserIds: User["id"][]; - - @Index() - @Column('integer', { - default: 0, - }) - public attachedRemoteUsersCount: number; -} diff --git a/packages/backend/src/models/entities/instance.ts b/packages/backend/src/models/entities/instance.ts deleted file mode 100644 index 2b118455db..0000000000 --- a/packages/backend/src/models/entities/instance.ts +++ /dev/null @@ -1,164 +0,0 @@ -import { Entity, PrimaryColumn, Index, Column } from "typeorm"; -import { id } from "../id.js"; - -@Entity() -export class Instance { - @PrimaryColumn(id()) - public id: string; - - /** - * このインスタンスを捕捉した日時 - */ - @Index() - @Column('timestamp with time zone', { - comment: 'The caught date of the Instance.', - }) - public caughtAt: Date; - - /** - * ホスト - */ - @Index({ unique: true }) - @Column('varchar', { - length: 128, - comment: 'The host of the Instance.', - }) - public host: string; - - /** - * インスタンスのユーザー数 - */ - @Column('integer', { - default: 0, - comment: 'The count of the users of the Instance.', - }) - public usersCount: number; - - /** - * インスタンスの投稿数 - */ - @Column('integer', { - default: 0, - comment: 'The count of the notes of the Instance.', - }) - public notesCount: number; - - /** - * このインスタンスのユーザーからフォローされている、自インスタンスのユーザーの数 - */ - @Column('integer', { - default: 0, - }) - public followingCount: number; - - /** - * このインスタンスのユーザーをフォローしている、自インスタンスのユーザーの数 - */ - @Column('integer', { - default: 0, - }) - public followersCount: number; - - /** - * 直近のリクエスト送信日時 - */ - @Column('timestamp with time zone', { - nullable: true, - }) - public latestRequestSentAt: Date | null; - - /** - * 直近のリクエスト送信時のHTTPステータスコード - */ - @Column('integer', { - nullable: true, - }) - public latestStatus: number | null; - - /** - * 直近のリクエスト受信日時 - */ - @Column('timestamp with time zone', { - nullable: true, - }) - public latestRequestReceivedAt: Date | null; - - /** - * このインスタンスと最後にやり取りした日時 - */ - @Column('timestamp with time zone') - public lastCommunicatedAt: Date; - - /** - * このインスタンスと不通かどうか - */ - @Column('boolean', { - default: false, - }) - public isNotResponding: boolean; - - /** - * このインスタンスへの配信を停止するか - */ - @Index() - @Column('boolean', { - default: false, - }) - public isSuspended: boolean; - - @Column('varchar', { - length: 64, nullable: true, - comment: 'The software of the Instance.', - }) - public softwareName: string | null; - - @Column('varchar', { - length: 64, nullable: true, - }) - public softwareVersion: string | null; - - @Column('boolean', { - nullable: true, - }) - public openRegistrations: boolean | null; - - @Column('varchar', { - length: 256, nullable: true, - }) - public name: string | null; - - @Column('varchar', { - length: 4096, nullable: true, - }) - public description: string | null; - - @Column('varchar', { - length: 128, nullable: true, - }) - public maintainerName: string | null; - - @Column('varchar', { - length: 256, nullable: true, - }) - public maintainerEmail: string | null; - - @Column('varchar', { - length: 256, nullable: true, - }) - public iconUrl: string | null; - - @Column('varchar', { - length: 256, nullable: true, - }) - public faviconUrl: string | null; - - @Column('varchar', { - length: 64, nullable: true, - }) - public themeColor: string | null; - - @Column('timestamp with time zone', { - nullable: true, - }) - public infoUpdatedAt: Date | null; -} diff --git a/packages/backend/src/models/entities/messaging-message.ts b/packages/backend/src/models/entities/messaging-message.ts deleted file mode 100644 index 9cf197fa3b..0000000000 --- a/packages/backend/src/models/entities/messaging-message.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { DriveFile } from "./drive-file.js"; -import { id } from "../id.js"; -import { UserGroup } from "./user-group.js"; - -@Entity() -export class MessagingMessage { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the MessagingMessage.', - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - comment: 'The sender user ID.', - }) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Index() - @Column({ - ...id(), nullable: true, - comment: 'The recipient user ID.', - }) - public recipientId: User["id"] | null; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public recipient: User | null; - - @Index() - @Column({ - ...id(), nullable: true, - comment: 'The recipient group ID.', - }) - public groupId: UserGroup["id"] | null; - - @ManyToOne(type => UserGroup, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public group: UserGroup | null; - - @Column('varchar', { - length: 4096, nullable: true, - }) - public text: string | null; - - @Column('boolean', { - default: false, - }) - public isRead: boolean; - - @Column('varchar', { - length: 512, nullable: true, - }) - public uri: string | null; - - @Column({ - ...id(), - array: true, default: '{}', - }) - public reads: User["id"][]; - - @Column({ - ...id(), - nullable: true, - }) - public fileId: DriveFile["id"] | null; - - @ManyToOne(type => DriveFile, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public file: DriveFile | null; -} diff --git a/packages/backend/src/models/entities/meta.ts b/packages/backend/src/models/entities/meta.ts deleted file mode 100644 index 26a7c9c193..0000000000 --- a/packages/backend/src/models/entities/meta.ts +++ /dev/null @@ -1,502 +0,0 @@ -import { Entity, Column, PrimaryColumn, ManyToOne, JoinColumn } from "typeorm"; -import { id } from "../id.js"; -import { User } from "./user.js"; -import type { Clip } from "./clip.js"; - -@Entity() -export class Meta { - @PrimaryColumn({ - type: 'varchar', - length: 32, - }) - public id: string; - - @Column('varchar', { - length: 128, nullable: true, - }) - public name: string | null; - - @Column('varchar', { - length: 1024, nullable: true, - }) - public description: string | null; - - /** - * メンテナの名前 - */ - @Column('varchar', { - length: 128, nullable: true, - }) - public maintainerName: string | null; - - /** - * メンテナの連絡先 - */ - @Column('varchar', { - length: 128, nullable: true, - }) - public maintainerEmail: string | null; - - @Column('boolean', { - default: false, - }) - public disableRegistration: boolean; - - @Column('boolean', { - default: false, - }) - public disableLocalTimeline: boolean; - - @Column('boolean', { - default: true, - }) - public disableRecommendedTimeline: boolean; - - @Column('boolean', { - default: false, - }) - public disableGlobalTimeline: boolean; - - @Column('varchar', { - length: 256, default: '⭐', - }) - public defaultReaction: string; - - @Column('varchar', { - length: 64, array: true, default: '{}', - }) - public langs: string[]; - - @Column('varchar', { - length: 256, array: true, default: '{}', - }) - public pinnedUsers: string[]; - - @Column('varchar', { - length: 256, array: true, default: '{}', - }) - public recommendedInstances: string[]; - - @Column('varchar', { - length: 256, array: true, default: '{}', - }) - public customMOTD: string[]; - - @Column('varchar', { - length: 256, array: true, default: '{}', - }) - public customSplashIcons: string[]; - - @Column('varchar', { - length: 256, array: true, default: '{}', - }) - public hiddenTags: string[]; - - @Column('varchar', { - length: 256, array: true, default: '{}', - }) - public blockedHosts: string[]; - - @Column('boolean', { - default: false, - }) - public secureMode: boolean; - - @Column('boolean', { - default: false, - }) - public privateMode: boolean; - - @Column('varchar', { - length: 256, array: true, default: '{}', - }) - public allowedHosts: string[]; - - @Column('varchar', { - length: 512, array: true, default: '{/featured,/channels,/explore,/pages,/about-calckey}', - }) - public pinnedPages: string[]; - - @Column({ - ...id(), - nullable: true, - }) - public pinnedClipId: Clip["id"] | null; - - @Column('varchar', { - length: 512, - nullable: true, - }) - public themeColor: string | null; - - @Column('varchar', { - length: 512, - nullable: true, - default: '/assets/ai.png', - }) - public mascotImageUrl: string | null; - - @Column('varchar', { - length: 512, - nullable: true, - }) - public bannerUrl: string | null; - - @Column('varchar', { - length: 512, - nullable: true, - }) - public backgroundImageUrl: string | null; - - @Column('varchar', { - length: 512, - nullable: true, - }) - public logoImageUrl: string | null; - - @Column('varchar', { - length: 512, - nullable: true, - default: 'https://xn--931a.moe/aiart/yubitun.png', - }) - public errorImageUrl: string | null; - - @Column('varchar', { - length: 512, - nullable: true, - }) - public iconUrl: string | null; - - @Column('boolean', { - default: true, - }) - public cacheRemoteFiles: boolean; - - @Column({ - ...id(), - nullable: true, - }) - public proxyAccountId: User["id"] | null; - - @ManyToOne(type => User, { - onDelete: 'SET NULL', - }) - @JoinColumn() - public proxyAccount: User | null; - - @Column('boolean', { - default: false, - }) - public emailRequiredForSignup: boolean; - - @Column('boolean', { - default: false, - }) - public enableHcaptcha: boolean; - - @Column('varchar', { - length: 64, - nullable: true, - }) - public hcaptchaSiteKey: string | null; - - @Column('varchar', { - length: 64, - nullable: true, - }) - public hcaptchaSecretKey: string | null; - - @Column('boolean', { - default: false, - }) - public enableRecaptcha: boolean; - - @Column('varchar', { - length: 64, - nullable: true, - }) - public recaptchaSiteKey: string | null; - - @Column('varchar', { - length: 64, - nullable: true, - }) - public recaptchaSecretKey: string | null; - - @Column('enum', { - enum: ['none', 'all', 'local', 'remote'], - default: 'none', - }) - public sensitiveMediaDetection: "none" | "all" | "local" | "remote"; - - @Column('enum', { - enum: ['medium', 'low', 'high', 'veryLow', 'veryHigh'], - default: 'medium', - }) - public sensitiveMediaDetectionSensitivity: - | "medium" - | "low" - | "high" - | "veryLow" - | "veryHigh"; - - @Column('boolean', { - default: false, - }) - public setSensitiveFlagAutomatically: boolean; - - @Column('boolean', { - default: false, - }) - public enableSensitiveMediaDetectionForVideos: boolean; - - @Column('integer', { - default: 1024, - comment: 'Drive capacity of a local user (MB)', - }) - public localDriveCapacityMb: number; - - @Column('integer', { - default: 32, - comment: 'Drive capacity of a remote user (MB)', - }) - public remoteDriveCapacityMb: number; - - @Column('varchar', { - length: 128, - nullable: true, - }) - public summalyProxy: string | null; - - @Column('boolean', { - default: false, - }) - public enableEmail: boolean; - - @Column('varchar', { - length: 128, - nullable: true, - }) - public email: string | null; - - @Column('boolean', { - default: false, - }) - public smtpSecure: boolean; - - @Column('varchar', { - length: 128, - nullable: true, - }) - public smtpHost: string | null; - - @Column('integer', { - nullable: true, - }) - public smtpPort: number | null; - - @Column('varchar', { - length: 128, - nullable: true, - }) - public smtpUser: string | null; - - @Column('varchar', { - length: 128, - nullable: true, - }) - public smtpPass: string | null; - - @Column('boolean', { - default: false, - }) - public enableServiceWorker: boolean; - - @Column('varchar', { - length: 128, - nullable: true, - }) - public swPublicKey: string | null; - - @Column('varchar', { - length: 128, - nullable: true, - }) - public swPrivateKey: string | null; - - @Column('boolean', { - default: false, - }) - public enableTwitterIntegration: boolean; - - @Column('varchar', { - length: 128, - nullable: true, - }) - public twitterConsumerKey: string | null; - - @Column('varchar', { - length: 128, - nullable: true, - }) - public twitterConsumerSecret: string | null; - - @Column('boolean', { - default: false, - }) - public enableGithubIntegration: boolean; - - @Column('varchar', { - length: 128, - nullable: true, - }) - public githubClientId: string | null; - - @Column('varchar', { - length: 128, - nullable: true, - }) - public githubClientSecret: string | null; - - @Column('boolean', { - default: false, - }) - public enableDiscordIntegration: boolean; - - @Column('varchar', { - length: 128, - nullable: true, - }) - public discordClientId: string | null; - - @Column('varchar', { - length: 128, - nullable: true, - }) - public discordClientSecret: string | null; - - @Column('varchar', { - length: 128, - nullable: true, - }) - public deeplAuthKey: string | null; - - @Column('boolean', { - default: false, - }) - public deeplIsPro: boolean; - - @Column('varchar', { - length: 512, - nullable: true, - }) - public ToSUrl: string | null; - - @Column('varchar', { - length: 512, - default: 'https://codeberg.org/calckey/calckey', - nullable: false, - }) - public repositoryUrl: string; - - @Column('varchar', { - length: 512, - default: 'https://codeberg.org/calckey/calckey/issues/new', - nullable: true, - }) - public feedbackUrl: string | null; - - @Column('varchar', { - length: 8192, - nullable: true, - }) - public defaultLightTheme: string | null; - - @Column('varchar', { - length: 8192, - nullable: true, - }) - public defaultDarkTheme: string | null; - - @Column('boolean', { - default: false, - }) - public useObjectStorage: boolean; - - @Column('varchar', { - length: 512, - nullable: true, - }) - public objectStorageBucket: string | null; - - @Column('varchar', { - length: 512, - nullable: true, - }) - public objectStoragePrefix: string | null; - - @Column('varchar', { - length: 512, - nullable: true, - }) - public objectStorageBaseUrl: string | null; - - @Column('varchar', { - length: 512, - nullable: true, - }) - public objectStorageEndpoint: string | null; - - @Column('varchar', { - length: 512, - nullable: true, - }) - public objectStorageRegion: string | null; - - @Column('varchar', { - length: 512, - nullable: true, - }) - public objectStorageAccessKey: string | null; - - @Column('varchar', { - length: 512, - nullable: true, - }) - public objectStorageSecretKey: string | null; - - @Column('integer', { - nullable: true, - }) - public objectStoragePort: number | null; - - @Column('boolean', { - default: true, - }) - public objectStorageUseSSL: boolean; - - @Column('boolean', { - default: true, - }) - public objectStorageUseProxy: boolean; - - @Column('boolean', { - default: false, - }) - public objectStorageSetPublicRead: boolean; - - @Column('boolean', { - default: true, - }) - public objectStorageS3ForcePathStyle: boolean; - - @Column('boolean', { - default: false, - }) - public enableIpLogging: boolean; - - @Column('boolean', { - default: true, - }) - public enableActiveEmailValidation: boolean; -} diff --git a/packages/backend/src/models/entities/moderation-log.ts b/packages/backend/src/models/entities/moderation-log.ts deleted file mode 100644 index cc745e0d20..0000000000 --- a/packages/backend/src/models/entities/moderation-log.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -export class ModerationLog { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the ModerationLog.', - }) - public createdAt: Date; - - @Index() - @Column(id()) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column('varchar', { - length: 128, - }) - public type: string; - - @Column('jsonb') - public info: Record<string, any>; -} diff --git a/packages/backend/src/models/entities/muted-note.ts b/packages/backend/src/models/entities/muted-note.ts deleted file mode 100644 index 11a6ae95d0..0000000000 --- a/packages/backend/src/models/entities/muted-note.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { - Entity, - Index, - JoinColumn, - Column, - ManyToOne, - PrimaryColumn, -} from "typeorm"; -import { Note } from "./note.js"; -import { User } from "./user.js"; -import { id } from "../id.js"; -import { mutedNoteReasons } from "../../types.js"; - -@Entity() -@Index(['noteId', 'userId'], { unique: true }) -export class MutedNote { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column({ - ...id(), - comment: 'The note ID.', - }) - public noteId: Note["id"]; - - @ManyToOne(type => Note, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public note: Note | null; - - @Index() - @Column({ - ...id(), - comment: 'The user ID.', - }) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - /** - * ミュートされた理由。 - */ - @Index() - @Column('enum', { - enum: mutedNoteReasons, - comment: 'The reason of the MutedNote.', - }) - public reason: typeof mutedNoteReasons[number]; -} diff --git a/packages/backend/src/models/entities/muting.ts b/packages/backend/src/models/entities/muting.ts deleted file mode 100644 index 561bcfb95f..0000000000 --- a/packages/backend/src/models/entities/muting.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['muterId', 'muteeId'], { unique: true }) -export class Muting { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the Muting.', - }) - public createdAt: Date; - - @Index() - @Column('timestamp with time zone', { - nullable: true, - }) - public expiresAt: Date | null; - - @Index() - @Column({ - ...id(), - comment: 'The mutee user ID.', - }) - public muteeId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public mutee: User | null; - - @Index() - @Column({ - ...id(), - comment: 'The muter user ID.', - }) - public muterId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public muter: User | null; -} diff --git a/packages/backend/src/models/entities/note-favorite.ts b/packages/backend/src/models/entities/note-favorite.ts deleted file mode 100644 index ab12d8b1b3..0000000000 --- a/packages/backend/src/models/entities/note-favorite.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { Note } from "./note.js"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['userId', 'noteId'], { unique: true }) -export class NoteFavorite { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the NoteFavorite.', - }) - public createdAt: Date; - - @Index() - @Column(id()) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column(id()) - public noteId: Note["id"]; - - @ManyToOne(type => Note, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public note: Note | null; -} diff --git a/packages/backend/src/models/entities/note-reaction.ts b/packages/backend/src/models/entities/note-reaction.ts deleted file mode 100644 index 0e51c33b16..0000000000 --- a/packages/backend/src/models/entities/note-reaction.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { Note } from "./note.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['userId', 'noteId'], { unique: true }) -export class NoteReaction { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the NoteReaction.', - }) - public createdAt: Date; - - @Index() - @Column(id()) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user?: User | null; - - @Index() - @Column(id()) - public noteId: Note["id"]; - - @ManyToOne(type => Note, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public note?: Note | null; - - // TODO: 対象noteのuserIdを非正規化したい(「受け取ったリアクション一覧」のようなものを(JOIN無しで)実装したいため) - - @Column('varchar', { - length: 260, - }) - public reaction: string; -} diff --git a/packages/backend/src/models/entities/note-thread-muting.ts b/packages/backend/src/models/entities/note-thread-muting.ts deleted file mode 100644 index 2985b195f0..0000000000 --- a/packages/backend/src/models/entities/note-thread-muting.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { Note } from "./note.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['userId', 'threadId'], { unique: true }) -export class NoteThreadMuting { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - }) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Index() - @Column('varchar', { - length: 256, - }) - public threadId: string; -} diff --git a/packages/backend/src/models/entities/note-unread.ts b/packages/backend/src/models/entities/note-unread.ts deleted file mode 100644 index d5bba72212..0000000000 --- a/packages/backend/src/models/entities/note-unread.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { Note } from "./note.js"; -import { id } from "../id.js"; -import type { Channel } from "./channel.js"; - -@Entity() -@Index(['userId', 'noteId'], { unique: true }) -export class NoteUnread { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column(id()) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Index() - @Column(id()) - public noteId: Note["id"]; - - @ManyToOne(type => Note, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public note: Note | null; - - /** - * メンションか否か - */ - @Index() - @Column('boolean') - public isMentioned: boolean; - - /** - * ダイレクト投稿か否か - */ - @Index() - @Column('boolean') - public isSpecified: boolean; - - //#region Denormalized fields - @Index() - @Column({ - ...id(), - comment: '[Denormalized]', - }) - public noteUserId: User["id"]; - - @Index() - @Column({ - ...id(), - nullable: true, - comment: '[Denormalized]', - }) - public noteChannelId: Channel["id"] | null; - //#endregion -} diff --git a/packages/backend/src/models/entities/note-watching.ts b/packages/backend/src/models/entities/note-watching.ts deleted file mode 100644 index 7ac3e8e297..0000000000 --- a/packages/backend/src/models/entities/note-watching.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { Note } from "./note.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['userId', 'noteId'], { unique: true }) -export class NoteWatching { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the NoteWatching.', - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - comment: 'The watcher ID.', - }) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Index() - @Column({ - ...id(), - comment: 'The target Note ID.', - }) - public noteId: Note["id"]; - - @ManyToOne(type => Note, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public note: Note | null; - - //#region Denormalized fields - @Index() - @Column({ - ...id(), - comment: '[Denormalized]', - }) - public noteUserId: Note["userId"]; - //#endregion -} diff --git a/packages/backend/src/models/entities/note.ts b/packages/backend/src/models/entities/note.ts deleted file mode 100644 index fd6b170c0e..0000000000 --- a/packages/backend/src/models/entities/note.ts +++ /dev/null @@ -1,249 +0,0 @@ -import { - Entity, - Index, - JoinColumn, - Column, - PrimaryColumn, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import type { DriveFile } from "./drive-file.js"; -import { id } from "../id.js"; -import { noteVisibilities } from "../../types.js"; -import { Channel } from "./channel.js"; - -@Entity() -@Index('IDX_NOTE_TAGS', { synchronize: false }) -@Index('IDX_NOTE_MENTIONS', { synchronize: false }) -@Index('IDX_NOTE_VISIBLE_USER_IDS', { synchronize: false }) -export class Note { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the Note.', - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - nullable: true, - comment: 'The ID of reply target.', - }) - public replyId: Note["id"] | null; - - @ManyToOne(type => Note, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public reply: Note | null; - - @Index() - @Column({ - ...id(), - nullable: true, - comment: 'The ID of renote target.', - }) - public renoteId: Note["id"] | null; - - @ManyToOne(type => Note, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public renote: Note | null; - - @Index() - @Column('varchar', { - length: 256, nullable: true, - }) - public threadId: string | null; - - @Column('text', { - nullable: true, - }) - public text: string | null; - - @Column('varchar', { - length: 256, nullable: true, - }) - public name: string | null; - - @Column('varchar', { - length: 512, nullable: true, - }) - public cw: string | null; - - @Index() - @Column({ - ...id(), - comment: 'The ID of author.', - }) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column('boolean', { - default: false, - }) - public localOnly: boolean; - - @Column('smallint', { - default: 0, - }) - public renoteCount: number; - - @Column('smallint', { - default: 0, - }) - public repliesCount: number; - - @Column('jsonb', { - default: {}, - }) - public reactions: Record<string, number>; - - /** - * public ... 公開 - * home ... ホームタイムライン(ユーザーページのタイムライン含む)のみに流す - * followers ... フォロワーのみ - * specified ... visibleUserIds で指定したユーザーのみ - */ - @Column('enum', { enum: noteVisibilities }) - public visibility: typeof noteVisibilities[number]; - - @Index({ unique: true }) - @Column('varchar', { - length: 512, nullable: true, - comment: 'The URI of a note. it will be null when the note is local.', - }) - public uri: string | null; - - @Column('varchar', { - length: 512, nullable: true, - comment: 'The human readable url of a note. it will be null when the note is local.', - }) - public url: string | null; - - @Column('integer', { - default: 0, select: false, - }) - public score: number; - - @Index() - @Column({ - ...id(), - array: true, default: '{}', - }) - public fileIds: DriveFile["id"][]; - - @Index() - @Column('varchar', { - length: 256, array: true, default: '{}', - }) - public attachedFileTypes: string[]; - - @Index() - @Column({ - ...id(), - array: true, default: '{}', - }) - public visibleUserIds: User["id"][]; - - @Index() - @Column({ - ...id(), - array: true, default: '{}', - }) - public mentions: User["id"][]; - - @Column('text', { - default: '[]', - }) - public mentionedRemoteUsers: string; - - @Column('varchar', { - length: 128, array: true, default: '{}', - }) - public emojis: string[]; - - @Index() - @Column('varchar', { - length: 128, array: true, default: '{}', - }) - public tags: string[]; - - @Column('boolean', { - default: false, - }) - public hasPoll: boolean; - - @Index() - @Column({ - ...id(), - nullable: true, - comment: 'The ID of source channel.', - }) - public channelId: Channel["id"] | null; - - @ManyToOne(type => Channel, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public channel: Channel | null; - - //#region Denormalized fields - @Index() - @Column('varchar', { - length: 128, nullable: true, - comment: '[Denormalized]', - }) - public userHost: string | null; - - @Column({ - ...id(), - nullable: true, - comment: '[Denormalized]', - }) - public replyUserId: User["id"] | null; - - @Column('varchar', { - length: 128, nullable: true, - comment: '[Denormalized]', - }) - public replyUserHost: string | null; - - @Column({ - ...id(), - nullable: true, - comment: '[Denormalized]', - }) - public renoteUserId: User["id"] | null; - - @Column('varchar', { - length: 128, nullable: true, - comment: '[Denormalized]', - }) - public renoteUserHost: string | null; - //#endregion - - constructor(data: Partial<Note>) { - if (data == null) return; - - for (const [k, v] of Object.entries(data)) { - (this as any)[k] = v; - } - } -} - -export type IMentionedRemoteUsers = { - uri: string; - url?: string; - username: string; - host: string; -}[]; diff --git a/packages/backend/src/models/entities/notification.ts b/packages/backend/src/models/entities/notification.ts deleted file mode 100644 index 2c55e988f1..0000000000 --- a/packages/backend/src/models/entities/notification.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { - Entity, - Index, - JoinColumn, - ManyToOne, - Column, - PrimaryColumn, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; -import { Note } from "./note.js"; -import { FollowRequest } from "./follow-request.js"; -import { UserGroupInvitation } from "./user-group-invitation.js"; -import { AccessToken } from "./access-token.js"; -import { notificationTypes } from "@/types.js"; - -@Entity() -export class Notification { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the Notification.', - }) - public createdAt: Date; - - /** - * Notification Recipient ID - */ - @Index() - @Column({ - ...id(), - comment: 'The ID of recipient user of the Notification.', - }) - public notifieeId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public notifiee: User | null; - - /** - * Notification sender (initiator) - */ - @Index() - @Column({ - ...id(), - nullable: true, - comment: 'The ID of sender user of the Notification.', - }) - public notifierId: User["id"] | null; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public notifier: User | null; - - /** - * Notification types: - * follow - Follow request - * mention - User was referenced in a post. - * reply - A post that a user made (or was watching) has been replied to. - * renote - A post that a user made (or was watching) has been renoted. - * quote - A post that a user made (or was watching) has been quoted and renoted. - * reaction - (自分または自分がWatchしている)投稿にリアクションされた - * pollVote - (自分または自分がWatchしている)投稿のアンケートに投票された - * pollEnded - 自分のアンケートもしくは自分が投票したアンケートが終了した - * receiveFollowRequest - フォローリクエストされた - * followRequestAccepted - A follow request has been accepted. - * groupInvited - グループに招待された - * app - App notifications. - */ - @Index() - @Column('enum', { - enum: notificationTypes, - comment: 'The type of the Notification.', - }) - public type: typeof notificationTypes[number]; - - /** - * Whether the notification was read. - */ - @Index() - @Column('boolean', { - default: false, - comment: 'Whether the notification was read.', - }) - public isRead: boolean; - - @Column({ - ...id(), - nullable: true, - }) - public noteId: Note["id"] | null; - - @ManyToOne(type => Note, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public note: Note | null; - - @Column({ - ...id(), - nullable: true, - }) - public followRequestId: FollowRequest["id"] | null; - - @ManyToOne(type => FollowRequest, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public followRequest: FollowRequest | null; - - @Column({ - ...id(), - nullable: true, - }) - public userGroupInvitationId: UserGroupInvitation["id"] | null; - - @ManyToOne(type => UserGroupInvitation, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public userGroupInvitation: UserGroupInvitation | null; - - @Column('varchar', { - length: 128, nullable: true, - }) - public reaction: string | null; - - @Column('integer', { - nullable: true, - }) - public choice: number | null; - - /** - * App notification body - */ - @Column('varchar', { - length: 2048, nullable: true, - }) - public customBody: string | null; - - /** - * App notification header - * (If omitted, it is expected to be displayed with the app name) - */ - @Column('varchar', { - length: 256, nullable: true, - }) - public customHeader: string | null; - - /** - * App notification icon (URL) - * (If omitted, it is expected to be displayed as an app icon) - */ - @Column('varchar', { - length: 1024, nullable: true, - }) - public customIcon: string | null; - - /** - * App notification app (token for) - */ - @Index() - @Column({ - ...id(), - nullable: true, - }) - public appAccessTokenId: AccessToken["id"] | null; - - @ManyToOne(type => AccessToken, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public appAccessToken: AccessToken | null; -} diff --git a/packages/backend/src/models/entities/page-like.ts b/packages/backend/src/models/entities/page-like.ts deleted file mode 100644 index 75f4dc49b0..0000000000 --- a/packages/backend/src/models/entities/page-like.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; -import { Page } from "./page.js"; - -@Entity() -@Index(['userId', 'pageId'], { unique: true }) -export class PageLike { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone') - public createdAt: Date; - - @Index() - @Column(id()) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column(id()) - public pageId: Page["id"]; - - @ManyToOne(type => Page, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public page: Page | null; -} diff --git a/packages/backend/src/models/entities/page.ts b/packages/backend/src/models/entities/page.ts deleted file mode 100644 index 5fe9f52088..0000000000 --- a/packages/backend/src/models/entities/page.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { - Entity, - Index, - JoinColumn, - Column, - PrimaryColumn, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; -import { DriveFile } from "./drive-file.js"; - -@Entity() -@Index(['userId', 'name'], { unique: true }) -export class Page { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the Page.', - }) - public createdAt: Date; - - @Index() - @Column('timestamp with time zone', { - comment: 'The updated date of the Page.', - }) - public updatedAt: Date; - - @Column('varchar', { - length: 256, - }) - public title: string; - - @Index() - @Column('varchar', { - length: 256, - }) - public name: string; - - @Column('varchar', { - length: 256, nullable: true, - }) - public summary: string | null; - - @Column('boolean') - public alignCenter: boolean; - - @Column('boolean') - public isPublic: boolean; - - @Column('boolean', { - default: false, - }) - public hideTitleWhenPinned: boolean; - - @Column('varchar', { - length: 32, - }) - public font: string; - - @Index() - @Column({ - ...id(), - comment: 'The ID of author.', - }) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column({ - ...id(), - nullable: true, - }) - public eyeCatchingImageId: DriveFile["id"] | null; - - @ManyToOne(type => DriveFile, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public eyeCatchingImage: DriveFile | null; - - @Column('jsonb', { - default: [], - }) - public content: Record<string, any>[]; - - @Column('jsonb', { - default: [], - }) - public variables: Record<string, any>[]; - - @Column('varchar', { - length: 16384, - default: '', - }) - public script: string; - - /** - * public ... 公開 - * followers ... フォロワーのみ - * specified ... visibleUserIds で指定したユーザーのみ - */ - @Column('enum', { enum: ['public', 'followers', 'specified'] }) - public visibility: "public" | "followers" | "specified"; - - @Index() - @Column({ - ...id(), - array: true, default: '{}', - }) - public visibleUserIds: User["id"][]; - - @Column('integer', { - default: 0, - }) - public likedCount: number; - - constructor(data: Partial<Page>) { - if (data == null) return; - - for (const [k, v] of Object.entries(data)) { - (this as any)[k] = v; - } - } -} diff --git a/packages/backend/src/models/entities/password-reset-request.ts b/packages/backend/src/models/entities/password-reset-request.ts deleted file mode 100644 index 4c681d4f70..0000000000 --- a/packages/backend/src/models/entities/password-reset-request.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - Column, - ManyToOne, - JoinColumn, -} from "typeorm"; -import { id } from "../id.js"; -import { User } from "./user.js"; - -@Entity() -export class PasswordResetRequest { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone') - public createdAt: Date; - - @Index({ unique: true }) - @Column('varchar', { - length: 256, - }) - public token: string; - - @Index() - @Column({ - ...id(), - }) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; -} diff --git a/packages/backend/src/models/entities/poll-vote.ts b/packages/backend/src/models/entities/poll-vote.ts deleted file mode 100644 index 0649951cf4..0000000000 --- a/packages/backend/src/models/entities/poll-vote.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { Note } from "./note.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['userId', 'noteId', 'choice'], { unique: true }) -export class PollVote { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the PollVote.', - }) - public createdAt: Date; - - @Index() - @Column(id()) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Index() - @Column(id()) - public noteId: Note["id"]; - - @ManyToOne(type => Note, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public note: Note | null; - - @Column('integer') - public choice: number; -} diff --git a/packages/backend/src/models/entities/poll.ts b/packages/backend/src/models/entities/poll.ts deleted file mode 100644 index 28a70b3c7b..0000000000 --- a/packages/backend/src/models/entities/poll.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - OneToOne, -} from "typeorm"; -import { id } from "../id.js"; -import { Note } from "./note.js"; -import type { User } from "./user.js"; -import { noteVisibilities } from "../../types.js"; - -@Entity() -export class Poll { - @PrimaryColumn(id()) - public noteId: Note["id"]; - - @OneToOne(type => Note, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public note: Note | null; - - @Column('timestamp with time zone', { - nullable: true, - }) - public expiresAt: Date | null; - - @Column('boolean') - public multiple: boolean; - - @Column('varchar', { - length: 256, array: true, default: '{}', - }) - public choices: string[]; - - @Column('integer', { - array: true, - }) - public votes: number[]; - - //#region Denormalized fields - @Column('enum', { - enum: noteVisibilities, - comment: '[Denormalized]', - }) - public noteVisibility: typeof noteVisibilities[number]; - - @Index() - @Column({ - ...id(), - comment: '[Denormalized]', - }) - public userId: User["id"]; - - @Index() - @Column('varchar', { - length: 128, nullable: true, - comment: '[Denormalized]', - }) - public userHost: string | null; - //#endregion - - constructor(data: Partial<Poll>) { - if (data == null) return; - - for (const [k, v] of Object.entries(data)) { - (this as any)[k] = v; - } - } -} - -export type IPoll = { - choices: string[]; - votes?: number[]; - multiple: boolean; - expiresAt: Date | null; -}; diff --git a/packages/backend/src/models/entities/promo-note.ts b/packages/backend/src/models/entities/promo-note.ts deleted file mode 100644 index 4daacd246a..0000000000 --- a/packages/backend/src/models/entities/promo-note.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - OneToOne, -} from "typeorm"; -import { Note } from "./note.js"; -import type { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -export class PromoNote { - @PrimaryColumn(id()) - public noteId: Note["id"]; - - @OneToOne(type => Note, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public note: Note | null; - - @Column('timestamp with time zone') - public expiresAt: Date; - - //#region Denormalized fields - @Index() - @Column({ - ...id(), - comment: '[Denormalized]', - }) - public userId: User["id"]; - //#endregion -} diff --git a/packages/backend/src/models/entities/promo-read.ts b/packages/backend/src/models/entities/promo-read.ts deleted file mode 100644 index 5938bfde9d..0000000000 --- a/packages/backend/src/models/entities/promo-read.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { Note } from "./note.js"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['userId', 'noteId'], { unique: true }) -export class PromoRead { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the PromoRead.', - }) - public createdAt: Date; - - @Index() - @Column(id()) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column(id()) - public noteId: Note["id"]; - - @ManyToOne(type => Note, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public note: Note | null; -} diff --git a/packages/backend/src/models/entities/registration-tickets.ts b/packages/backend/src/models/entities/registration-tickets.ts deleted file mode 100644 index af785fbc0d..0000000000 --- a/packages/backend/src/models/entities/registration-tickets.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { PrimaryColumn, Entity, Index, Column } from "typeorm"; -import { id } from "../id.js"; - -@Entity() -export class RegistrationTicket { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone') - public createdAt: Date; - - @Index({ unique: true }) - @Column('varchar', { - length: 64, - }) - public code: string; -} diff --git a/packages/backend/src/models/entities/registry-item.ts b/packages/backend/src/models/entities/registry-item.ts deleted file mode 100644 index 655573883a..0000000000 --- a/packages/backend/src/models/entities/registry-item.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -// TODO: 同じdomain、同じscope、同じkeyのレコードは二つ以上存在しないように制約付けたい -@Entity() -export class RegistryItem { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the RegistryItem.', - }) - public createdAt: Date; - - @Column('timestamp with time zone', { - comment: 'The updated date of the RegistryItem.', - }) - public updatedAt: Date; - - @Index() - @Column({ - ...id(), - comment: 'The owner ID.', - }) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column('varchar', { - length: 1024, - comment: 'The key of the RegistryItem.', - }) - public key: string; - - @Column('jsonb', { - default: {}, nullable: true, - comment: 'The value of the RegistryItem.', - }) - public value: any | null; - - @Index() - @Column('varchar', { - length: 1024, array: true, default: '{}', - }) - public scope: string[]; - - // サードパーティアプリに開放するときのためのカラム - @Index() - @Column('varchar', { - length: 512, nullable: true, - }) - public domain: string | null; -} diff --git a/packages/backend/src/models/entities/relay.ts b/packages/backend/src/models/entities/relay.ts deleted file mode 100644 index 82c0779ff8..0000000000 --- a/packages/backend/src/models/entities/relay.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { PrimaryColumn, Entity, Index, Column } from "typeorm"; -import { id } from "../id.js"; - -@Entity() -export class Relay { - @PrimaryColumn(id()) - public id: string; - - @Index({ unique: true }) - @Column('varchar', { - length: 512, nullable: false, - }) - public inbox: string; - - @Column('enum', { - enum: ['requesting', 'accepted', 'rejected'], - }) - public status: "requesting" | "accepted" | "rejected"; -} diff --git a/packages/backend/src/models/entities/renote-muting.ts b/packages/backend/src/models/entities/renote-muting.ts deleted file mode 100644 index 64ec7f583f..0000000000 --- a/packages/backend/src/models/entities/renote-muting.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { id } from "../id.js"; -import { User } from "./user.js"; - -@Entity() -@Index(["muterId", "muteeId"], { unique: true }) -export class RenoteMuting { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column("timestamp with time zone", { - comment: "The created date of the Muting.", - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - comment: "The mutee user ID.", - }) - public muteeId: User["id"]; - - @ManyToOne(type => User, { - onDelete: "CASCADE", - }) - @JoinColumn() - public mutee: User | null; - - @Index() - @Column({ - ...id(), - comment: "The muter user ID.", - }) - public muterId: User["id"]; - - @ManyToOne(type => User, { - onDelete: "CASCADE", - }) - @JoinColumn() - public muter: User | null; -} diff --git a/packages/backend/src/models/entities/signin.ts b/packages/backend/src/models/entities/signin.ts deleted file mode 100644 index 7859918238..0000000000 --- a/packages/backend/src/models/entities/signin.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -export class Signin { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the Signin.', - }) - public createdAt: Date; - - @Index() - @Column(id()) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column('varchar', { - length: 128, - }) - public ip: string; - - @Column('jsonb') - public headers: Record<string, any>; - - @Column('boolean') - public success: boolean; -} diff --git a/packages/backend/src/models/entities/sw-subscription.ts b/packages/backend/src/models/entities/sw-subscription.ts deleted file mode 100644 index 8f18688eab..0000000000 --- a/packages/backend/src/models/entities/sw-subscription.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -export class SwSubscription { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone') - public createdAt: Date; - - @Index() - @Column(id()) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column('varchar', { - length: 512, - }) - public endpoint: string; - - @Column('varchar', { - length: 256, - }) - public auth: string; - - @Column('varchar', { - length: 128, - }) - public publickey: string; - - @Column('boolean', { - default: false, - }) - public sendReadMessage: boolean; -} diff --git a/packages/backend/src/models/entities/used-username.ts b/packages/backend/src/models/entities/used-username.ts deleted file mode 100644 index a069205a5f..0000000000 --- a/packages/backend/src/models/entities/used-username.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { PrimaryColumn, Entity, Column } from "typeorm"; - -@Entity() -export class UsedUsername { - @PrimaryColumn('varchar', { - length: 128, - }) - public username: string; - - @Column('timestamp with time zone') - public createdAt: Date; - - constructor(data: Partial<UsedUsername>) { - if (data == null) return; - - for (const [k, v] of Object.entries(data)) { - (this as any)[k] = v; - } - } -} diff --git a/packages/backend/src/models/entities/user-group-invitation.ts b/packages/backend/src/models/entities/user-group-invitation.ts deleted file mode 100644 index 8037b30e1b..0000000000 --- a/packages/backend/src/models/entities/user-group-invitation.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { UserGroup } from "./user-group.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['userId', 'userGroupId'], { unique: true }) -export class UserGroupInvitation { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the UserGroupInvitation.', - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - comment: 'The user ID.', - }) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Index() - @Column({ - ...id(), - comment: 'The group ID.', - }) - public userGroupId: UserGroup["id"]; - - @ManyToOne(type => UserGroup, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public userGroup: UserGroup | null; -} diff --git a/packages/backend/src/models/entities/user-group-joining.ts b/packages/backend/src/models/entities/user-group-joining.ts deleted file mode 100644 index 6d503b274e..0000000000 --- a/packages/backend/src/models/entities/user-group-joining.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { UserGroup } from "./user-group.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['userId', 'userGroupId'], { unique: true }) -export class UserGroupJoining { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the UserGroupJoining.', - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - comment: 'The user ID.', - }) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Index() - @Column({ - ...id(), - comment: 'The group ID.', - }) - public userGroupId: UserGroup["id"]; - - @ManyToOne(type => UserGroup, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public userGroup: UserGroup | null; -} diff --git a/packages/backend/src/models/entities/user-group.ts b/packages/backend/src/models/entities/user-group.ts deleted file mode 100644 index 38e5af3346..0000000000 --- a/packages/backend/src/models/entities/user-group.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { - Entity, - Index, - JoinColumn, - Column, - PrimaryColumn, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -export class UserGroup { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the UserGroup.', - }) - public createdAt: Date; - - @Column('varchar', { - length: 256, - }) - public name: string; - - @Index() - @Column({ - ...id(), - comment: 'The ID of owner.', - }) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column('boolean', { - default: false, - }) - public isPrivate: boolean; - - constructor(data: Partial<UserGroup>) { - if (data == null) return; - - for (const [k, v] of Object.entries(data)) { - (this as any)[k] = v; - } - } -} diff --git a/packages/backend/src/models/entities/user-ip.ts b/packages/backend/src/models/entities/user-ip.ts deleted file mode 100644 index 6b88d52216..0000000000 --- a/packages/backend/src/models/entities/user-ip.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, - PrimaryGeneratedColumn, -} from "typeorm"; -import { id } from "../id.js"; -import { Note } from "./note.js"; -import type { User } from "./user.js"; - -@Entity() -@Index(['userId', 'ip'], { unique: true }) -export class UserIp { - @PrimaryGeneratedColumn() - public id: string; - - @Column('timestamp with time zone', { - }) - public createdAt: Date; - - @Index() - @Column(id()) - public userId: User["id"]; - - @Column('varchar', { - length: 128, - }) - public ip: string; -} diff --git a/packages/backend/src/models/entities/user-keypair.ts b/packages/backend/src/models/entities/user-keypair.ts deleted file mode 100644 index 212e742b9e..0000000000 --- a/packages/backend/src/models/entities/user-keypair.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { PrimaryColumn, Entity, JoinColumn, Column, OneToOne } from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -export class UserKeypair { - @PrimaryColumn(id()) - public userId: User["id"]; - - @OneToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column('varchar', { - length: 4096, - }) - public publicKey: string; - - @Column('varchar', { - length: 4096, - }) - public privateKey: string; - - constructor(data: Partial<UserKeypair>) { - if (data == null) return; - - for (const [k, v] of Object.entries(data)) { - (this as any)[k] = v; - } - } -} diff --git a/packages/backend/src/models/entities/user-list-joining.ts b/packages/backend/src/models/entities/user-list-joining.ts deleted file mode 100644 index e52fa7b399..0000000000 --- a/packages/backend/src/models/entities/user-list-joining.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { UserList } from "./user-list.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['userId', 'userListId'], { unique: true }) -export class UserListJoining { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the UserListJoining.', - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - comment: 'The user ID.', - }) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Index() - @Column({ - ...id(), - comment: 'The list ID.', - }) - public userListId: UserList["id"]; - - @ManyToOne(type => UserList, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public userList: UserList | null; -} diff --git a/packages/backend/src/models/entities/user-list.ts b/packages/backend/src/models/entities/user-list.ts deleted file mode 100644 index 7c43452308..0000000000 --- a/packages/backend/src/models/entities/user-list.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -export class UserList { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the UserList.', - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - comment: 'The owner ID.', - }) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column('varchar', { - length: 128, - comment: 'The name of the UserList.', - }) - public name: string; -} diff --git a/packages/backend/src/models/entities/user-note-pining.ts b/packages/backend/src/models/entities/user-note-pining.ts deleted file mode 100644 index dc6d61f7e5..0000000000 --- a/packages/backend/src/models/entities/user-note-pining.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { Note } from "./note.js"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -@Index(['userId', 'noteId'], { unique: true }) -export class UserNotePining { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the UserNotePinings.', - }) - public createdAt: Date; - - @Index() - @Column(id()) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column(id()) - public noteId: Note["id"]; - - @ManyToOne(type => Note, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public note: Note | null; -} diff --git a/packages/backend/src/models/entities/user-pending.ts b/packages/backend/src/models/entities/user-pending.ts deleted file mode 100644 index cac85d1c02..0000000000 --- a/packages/backend/src/models/entities/user-pending.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { PrimaryColumn, Entity, Index, Column } from "typeorm"; -import { id } from "../id.js"; - -@Entity() -export class UserPending { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone') - public createdAt: Date; - - @Index({ unique: true }) - @Column('varchar', { - length: 128, - }) - public code: string; - - @Column('varchar', { - length: 128, - }) - public username: string; - - @Column('varchar', { - length: 128, - }) - public email: string; - - @Column('varchar', { - length: 128, - }) - public password: string; -} diff --git a/packages/backend/src/models/entities/user-profile.ts b/packages/backend/src/models/entities/user-profile.ts deleted file mode 100644 index cc3d238679..0000000000 --- a/packages/backend/src/models/entities/user-profile.ts +++ /dev/null @@ -1,239 +0,0 @@ -import { - Entity, - Column, - Index, - OneToOne, - JoinColumn, - PrimaryColumn, -} from "typeorm"; -import { ffVisibility, notificationTypes } from "@/types.js"; -import { id } from "../id.js"; -import { User } from "./user.js"; -import { Page } from "./page.js"; - -// TODO: このテーブルで管理している情報すべてレジストリで管理するようにしても良いかも -// ただ、「emailVerified が true なユーザーを find する」のようなクエリは書けなくなるからウーン -@Entity() -export class UserProfile { - @PrimaryColumn(id()) - public userId: User["id"]; - - @OneToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column('varchar', { - length: 128, nullable: true, - comment: 'The location of the User.', - }) - public location: string | null; - - @Column('char', { - length: 10, nullable: true, - comment: 'The birthday (YYYY-MM-DD) of the User.', - }) - public birthday: string | null; - - @Column('varchar', { - length: 2048, nullable: true, - comment: 'The description (bio) of the User.', - }) - public description: string | null; - - @Column('jsonb', { - default: [], - }) - public fields: { - name: string; - value: string; - }[]; - - @Column('varchar', { - length: 32, nullable: true, - }) - public lang: string | null; - - @Column('varchar', { - length: 512, nullable: true, - comment: 'Remote URL of the user.', - }) - public url: string | null; - - @Column('varchar', { - length: 128, nullable: true, - comment: 'The email address of the User.', - }) - public email: string | null; - - @Column('varchar', { - length: 128, nullable: true, - }) - public emailVerifyCode: string | null; - - @Column('boolean', { - default: false, - }) - public emailVerified: boolean; - - @Column('jsonb', { - default: ['follow', 'receiveFollowRequest', 'groupInvited'], - }) - public emailNotificationTypes: string[]; - - @Column('boolean', { - default: false, - }) - public publicReactions: boolean; - - @Column('enum', { - enum: ffVisibility, - default: 'public', - }) - public ffVisibility: typeof ffVisibility[number]; - - @Column('varchar', { - length: 128, nullable: true, - }) - public twoFactorTempSecret: string | null; - - @Column('varchar', { - length: 128, nullable: true, - }) - public twoFactorSecret: string | null; - - @Column('boolean', { - default: false, - }) - public twoFactorEnabled: boolean; - - @Column('boolean', { - default: false, - }) - public securityKeysAvailable: boolean; - - @Column('boolean', { - default: false, - }) - public usePasswordLessLogin: boolean; - - @Column('varchar', { - length: 128, nullable: true, - comment: 'The password hash of the User. It will be null if the origin of the user is local.', - }) - public password: string | null; - - @Column('varchar', { - length: 8192, default: '', - }) - public moderationNote: string | null; - - // TODO: そのうち消す - @Column('jsonb', { - default: {}, - comment: 'The client-specific data of the User.', - }) - public clientData: Record<string, any>; - - // TODO: そのうち消す - @Column('jsonb', { - default: {}, - comment: 'The room data of the User.', - }) - public room: Record<string, any>; - - @Column('boolean', { - default: false, - }) - public autoAcceptFollowed: boolean; - - @Column('boolean', { - default: false, - comment: 'Whether reject index by crawler.', - }) - public noCrawle: boolean; - - @Column('boolean', { - default: false, - }) - public alwaysMarkNsfw: boolean; - - @Column('boolean', { - default: false, - }) - public autoSensitive: boolean; - - @Column('boolean', { - default: false, - }) - public carefulBot: boolean; - - @Column('boolean', { - default: true, - }) - public injectFeaturedNote: boolean; - - @Column('boolean', { - default: true, - }) - public receiveAnnouncementEmail: boolean; - - @Column({ - ...id(), - nullable: true, - }) - public pinnedPageId: Page["id"] | null; - - @OneToOne(type => Page, { - onDelete: 'SET NULL', - }) - @JoinColumn() - public pinnedPage: Page | null; - - @Column('jsonb', { - default: {}, - }) - public integrations: Record<string, any>; - - @Index() - @Column('boolean', { - default: false, select: false, - }) - public enableWordMute: boolean; - - @Column('jsonb', { - default: [], - }) - public mutedWords: string[][]; - - @Column('jsonb', { - default: [], - comment: 'List of instances muted by the user.', - }) - public mutedInstances: string[]; - - @Column('enum', { - enum: notificationTypes, - array: true, - default: [], - }) - public mutingNotificationTypes: typeof notificationTypes[number][]; - - //#region Denormalized fields - @Index() - @Column('varchar', { - length: 128, nullable: true, - comment: '[Denormalized]', - }) - public userHost: string | null; - //#endregion - - constructor(data: Partial<UserProfile>) { - if (data == null) return; - - for (const [k, v] of Object.entries(data)) { - (this as any)[k] = v; - } - } -} diff --git a/packages/backend/src/models/entities/user-publickey.ts b/packages/backend/src/models/entities/user-publickey.ts deleted file mode 100644 index d1a9239d11..0000000000 --- a/packages/backend/src/models/entities/user-publickey.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - OneToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -export class UserPublickey { - @PrimaryColumn(id()) - public userId: User["id"]; - - @OneToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Index({ unique: true }) - @Column('varchar', { - length: 256, - }) - public keyId: string; - - @Column('varchar', { - length: 4096, - }) - public keyPem: string; - - constructor(data: Partial<UserPublickey>) { - if (data == null) return; - - for (const [k, v] of Object.entries(data)) { - (this as any)[k] = v; - } - } -} diff --git a/packages/backend/src/models/entities/user-security-key.ts b/packages/backend/src/models/entities/user-security-key.ts deleted file mode 100644 index 3b9d925d9e..0000000000 --- a/packages/backend/src/models/entities/user-security-key.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { - PrimaryColumn, - Entity, - JoinColumn, - Column, - ManyToOne, - Index, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -@Entity() -export class UserSecurityKey { - @PrimaryColumn('varchar', { - comment: 'Variable-length id given to navigator.credentials.get()', - }) - public id: string; - - @Index() - @Column(id()) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Index() - @Column('varchar', { - comment: - 'Variable-length public key used to verify attestations (hex-encoded).', - }) - public publicKey: string; - - @Column('timestamp with time zone', { - comment: - 'The date of the last time the UserSecurityKey was successfully validated.', - }) - public lastUsed: Date; - - @Column('varchar', { - comment: 'User-defined name for this key', - length: 30, - }) - public name: string; - - constructor(data: Partial<UserSecurityKey>) { - if (data == null) return; - - for (const [k, v] of Object.entries(data)) { - (this as any)[k] = v; - } - } -} diff --git a/packages/backend/src/models/entities/user.ts b/packages/backend/src/models/entities/user.ts deleted file mode 100644 index c23f4f28d7..0000000000 --- a/packages/backend/src/models/entities/user.ts +++ /dev/null @@ -1,274 +0,0 @@ -import { - Entity, - Column, - Index, - OneToOne, - JoinColumn, - PrimaryColumn, -} from "typeorm"; -import { id } from "../id.js"; -import { DriveFile } from "./drive-file.js"; - -@Entity() -@Index(['usernameLower', 'host'], { unique: true }) -export class User { - @PrimaryColumn(id()) - public id: string; - - @Index() - @Column('timestamp with time zone', { - comment: 'The created date of the User.', - }) - public createdAt: Date; - - @Index() - @Column('timestamp with time zone', { - nullable: true, - comment: 'The updated date of the User.', - }) - public updatedAt: Date | null; - - @Column('timestamp with time zone', { - nullable: true, - }) - public lastFetchedAt: Date | null; - - @Index() - @Column('timestamp with time zone', { - nullable: true, - }) - public lastActiveDate: Date | null; - - @Column('boolean', { - default: false, - }) - public hideOnlineStatus: boolean; - - @Column('varchar', { - length: 128, - comment: 'The username of the User.', - }) - public username: string; - - @Index() - @Column('varchar', { - length: 128, select: false, - comment: 'The username (lowercased) of the User.', - }) - public usernameLower: string; - - @Column('varchar', { - length: 128, nullable: true, - comment: 'The name of the User.', - }) - public name: string | null; - - @Column('integer', { - default: 0, - comment: 'The count of followers.', - }) - public followersCount: number; - - @Column('integer', { - default: 0, - comment: 'The count of following.', - }) - public followingCount: number; - - @Column('varchar', { - length: 512, - nullable: true, - comment: 'The URI of the new account of the User', - }) - public movedToUri: string | null; - - @Column('simple-array', { - nullable: true, - comment: 'URIs the user is known as too', - }) - public alsoKnownAs: string[] | null; - - @Column('integer', { - default: 0, - comment: 'The count of notes.', - }) - public notesCount: number; - - @Column({ - ...id(), - nullable: true, - comment: 'The ID of avatar DriveFile.', - }) - public avatarId: DriveFile["id"] | null; - - @OneToOne(type => DriveFile, { - onDelete: 'SET NULL', - }) - @JoinColumn() - public avatar: DriveFile | null; - - @Column({ - ...id(), - nullable: true, - comment: 'The ID of banner DriveFile.', - }) - public bannerId: DriveFile["id"] | null; - - @OneToOne(type => DriveFile, { - onDelete: 'SET NULL', - }) - @JoinColumn() - public banner: DriveFile | null; - - @Index() - @Column('varchar', { - length: 128, array: true, default: '{}', - }) - public tags: string[]; - - @Column('boolean', { - default: false, - comment: 'Whether the User is suspended.', - }) - public isSuspended: boolean; - - @Column('boolean', { - default: false, - comment: 'Whether the User is silenced.', - }) - public isSilenced: boolean; - - @Column('boolean', { - default: false, - comment: 'Whether the User is locked.', - }) - public isLocked: boolean; - - @Column('boolean', { - default: false, - comment: 'Whether the User is a bot.', - }) - public isBot: boolean; - - @Column('boolean', { - default: false, - comment: 'Whether the User is a cat.', - }) - public isCat: boolean; - - @Column('boolean', { - default: true, - comment: 'Whether to speak as a cat if isCat.', - }) - public speakAsCat: boolean; - - @Column('boolean', { - default: false, - comment: 'Whether the User is the admin.', - }) - public isAdmin: boolean; - - @Column('boolean', { - default: false, - comment: 'Whether the User is a moderator.', - }) - public isModerator: boolean; - - @Index() - @Column('boolean', { - default: true, - comment: 'Whether the User is explorable.', - }) - public isExplorable: boolean; - - // アカウントが削除されたかどうかのフラグだが、完全に削除される際は物理削除なので実質削除されるまでの「削除が進行しているかどうか」のフラグ - @Column('boolean', { - default: false, - comment: 'Whether the User is deleted.', - }) - public isDeleted: boolean; - - @Column('varchar', { - length: 128, array: true, default: '{}', - }) - public emojis: string[]; - - @Index() - @Column('varchar', { - length: 128, nullable: true, - comment: 'The host of the User. It will be null if the origin of the user is local.', - }) - public host: string | null; - - @Column('varchar', { - length: 512, nullable: true, - comment: 'The inbox URL of the User. It will be null if the origin of the user is local.', - }) - public inbox: string | null; - - @Column('varchar', { - length: 512, nullable: true, - comment: 'The sharedInbox URL of the User. It will be null if the origin of the user is local.', - }) - public sharedInbox: string | null; - - @Column('varchar', { - length: 512, nullable: true, - comment: 'The featured URL of the User. It will be null if the origin of the user is local.', - }) - public featured: string | null; - - @Index() - @Column('varchar', { - length: 512, nullable: true, - comment: 'The URI of the User. It will be null if the origin of the user is local.', - }) - public uri: string | null; - - @Column('varchar', { - length: 512, nullable: true, - comment: 'The URI of the user Follower Collection. It will be null if the origin of the user is local.', - }) - public followersUri: string | null; - - @Column('boolean', { - default: false, - comment: 'Whether to show users replying to other users in the timeline.', - }) - public showTimelineReplies: boolean; - - @Index({ unique: true }) - @Column('char', { - length: 16, nullable: true, unique: true, - comment: 'The native access token of the User. It will be null if the origin of the user is local.', - }) - public token: string | null; - - @Column('integer', { - nullable: true, - comment: 'Overrides user drive capacity limit', - }) - public driveCapacityOverrideMb: number | null; - - constructor(data: Partial<User>) { - if (data == null) return; - - for (const [k, v] of Object.entries(data)) { - (this as any)[k] = v; - } - } -} - -export interface ILocalUser extends User { - host: null; -} - -export interface IRemoteUser extends User { - host: string; -} - -export type CacheableLocalUser = ILocalUser; - -export type CacheableRemoteUser = IRemoteUser; - -export type CacheableUser = CacheableLocalUser | CacheableRemoteUser; diff --git a/packages/backend/src/models/entities/webhook.ts b/packages/backend/src/models/entities/webhook.ts deleted file mode 100644 index 5db51c3a3c..0000000000 --- a/packages/backend/src/models/entities/webhook.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { - PrimaryColumn, - Entity, - Index, - JoinColumn, - Column, - ManyToOne, -} from "typeorm"; -import { User } from "./user.js"; -import { id } from "../id.js"; - -export const webhookEventTypes = [ - "mention", - "unfollow", - "follow", - "followed", - "note", - "reply", - "renote", - "reaction", -] as const; - -@Entity() -export class Webhook { - @PrimaryColumn(id()) - public id: string; - - @Column('timestamp with time zone', { - comment: 'The created date of the Antenna.', - }) - public createdAt: Date; - - @Index() - @Column({ - ...id(), - comment: 'The owner ID.', - }) - public userId: User["id"]; - - @ManyToOne(type => User, { - onDelete: 'CASCADE', - }) - @JoinColumn() - public user: User | null; - - @Column('varchar', { - length: 128, - comment: 'The name of the Antenna.', - }) - public name: string; - - @Index() - @Column('varchar', { - length: 128, array: true, default: '{}', - }) - public on: typeof webhookEventTypes[number][]; - - @Column('varchar', { - length: 1024, - }) - public url: string; - - @Column('varchar', { - length: 1024, - }) - public secret: string; - - @Index() - @Column('boolean', { - default: true, - }) - public active: boolean; - - /** - * 直近のリクエスト送信日時 - */ - @Column('timestamp with time zone', { - nullable: true, - }) - public latestSentAt: Date | null; - - /** - * 直近のリクエスト送信時のHTTPステータスコード - */ - @Column('integer', { - nullable: true, - }) - public latestStatus: number | null; -} diff --git a/packages/backend/src/models/id.ts b/packages/backend/src/models/id.ts deleted file mode 100644 index 7e5a787984..0000000000 --- a/packages/backend/src/models/id.ts +++ /dev/null @@ -1,4 +0,0 @@ -export const id = () => ({ - type: "varchar" as const, - length: 32, -}); diff --git a/packages/backend/src/models/index.ts b/packages/backend/src/models/index.ts deleted file mode 100644 index f68166c17f..0000000000 --- a/packages/backend/src/models/index.ts +++ /dev/null @@ -1,135 +0,0 @@ -import {} from "typeorm"; -import { db } from "@/db/postgre.js"; - -import { Announcement } from "./entities/announcement.js"; -import { AnnouncementRead } from "./entities/announcement-read.js"; -import { Instance } from "./entities/instance.js"; -import { Poll } from "./entities/poll.js"; -import { PollVote } from "./entities/poll-vote.js"; -import { Meta } from "./entities/meta.js"; -import { SwSubscription } from "./entities/sw-subscription.js"; -import { NoteWatching } from "./entities/note-watching.js"; -import { NoteThreadMuting } from "./entities/note-thread-muting.js"; -import { NoteUnread } from "./entities/note-unread.js"; -import { RegistrationTicket } from "./entities/registration-tickets.js"; -import { UserRepository } from "./repositories/user.js"; -import { NoteRepository } from "./repositories/note.js"; -import { DriveFileRepository } from "./repositories/drive-file.js"; -import { DriveFolderRepository } from "./repositories/drive-folder.js"; -import { AccessToken } from "./entities/access-token.js"; -import { UserNotePining } from "./entities/user-note-pining.js"; -import { SigninRepository } from "./repositories/signin.js"; -import { MessagingMessageRepository } from "./repositories/messaging-message.js"; -import { UserListRepository } from "./repositories/user-list.js"; -import { UserListJoining } from "./entities/user-list-joining.js"; -import { UserGroupRepository } from "./repositories/user-group.js"; -import { UserGroupJoining } from "./entities/user-group-joining.js"; -import { UserGroupInvitationRepository } from "./repositories/user-group-invitation.js"; -import { FollowRequestRepository } from "./repositories/follow-request.js"; -import { MutingRepository } from "./repositories/muting.js"; -import { RenoteMutingRepository } from "./repositories/renote-muting.js"; -import { BlockingRepository } from "./repositories/blocking.js"; -import { NoteReactionRepository } from "./repositories/note-reaction.js"; -import { NotificationRepository } from "./repositories/notification.js"; -import { NoteFavoriteRepository } from "./repositories/note-favorite.js"; -import { UserPublickey } from "./entities/user-publickey.js"; -import { UserKeypair } from "./entities/user-keypair.js"; -import { AppRepository } from "./repositories/app.js"; -import { FollowingRepository } from "./repositories/following.js"; -import { AbuseUserReportRepository } from "./repositories/abuse-user-report.js"; -import { AuthSessionRepository } from "./repositories/auth-session.js"; -import { UserProfile } from "./entities/user-profile.js"; -import { AttestationChallenge } from "./entities/attestation-challenge.js"; -import { UserSecurityKey } from "./entities/user-security-key.js"; -import { HashtagRepository } from "./repositories/hashtag.js"; -import { PageRepository } from "./repositories/page.js"; -import { PageLikeRepository } from "./repositories/page-like.js"; -import { GalleryPostRepository } from "./repositories/gallery-post.js"; -import { GalleryLikeRepository } from "./repositories/gallery-like.js"; -import { ModerationLogRepository } from "./repositories/moderation-logs.js"; -import { UsedUsername } from "./entities/used-username.js"; -import { ClipRepository } from "./repositories/clip.js"; -import { ClipNote } from "./entities/clip-note.js"; -import { AntennaRepository } from "./repositories/antenna.js"; -import { AntennaNote } from "./entities/antenna-note.js"; -import { PromoNote } from "./entities/promo-note.js"; -import { PromoRead } from "./entities/promo-read.js"; -import { EmojiRepository } from "./repositories/emoji.js"; -import { RelayRepository } from "./repositories/relay.js"; -import { ChannelRepository } from "./repositories/channel.js"; -import { MutedNote } from "./entities/muted-note.js"; -import { ChannelFollowing } from "./entities/channel-following.js"; -import { ChannelNotePining } from "./entities/channel-note-pining.js"; -import { RegistryItem } from "./entities/registry-item.js"; -import { Ad } from "./entities/ad.js"; -import { PasswordResetRequest } from "./entities/password-reset-request.js"; -import { UserPending } from "./entities/user-pending.js"; -import { InstanceRepository } from "./repositories/instance.js"; -import { Webhook } from "./entities/webhook.js"; -import { UserIp } from "./entities/user-ip.js"; - -export const Announcements = db.getRepository(Announcement); -export const AnnouncementReads = db.getRepository(AnnouncementRead); -export const Apps = AppRepository; -export const Notes = NoteRepository; -export const NoteFavorites = NoteFavoriteRepository; -export const NoteWatchings = db.getRepository(NoteWatching); -export const NoteThreadMutings = db.getRepository(NoteThreadMuting); -export const NoteReactions = NoteReactionRepository; -export const NoteUnreads = db.getRepository(NoteUnread); -export const Polls = db.getRepository(Poll); -export const PollVotes = db.getRepository(PollVote); -export const Users = UserRepository; -export const UserProfiles = db.getRepository(UserProfile); -export const UserKeypairs = db.getRepository(UserKeypair); -export const UserPendings = db.getRepository(UserPending); -export const AttestationChallenges = db.getRepository(AttestationChallenge); -export const UserSecurityKeys = db.getRepository(UserSecurityKey); -export const UserPublickeys = db.getRepository(UserPublickey); -export const UserLists = UserListRepository; -export const UserListJoinings = db.getRepository(UserListJoining); -export const UserGroups = UserGroupRepository; -export const UserGroupJoinings = db.getRepository(UserGroupJoining); -export const UserGroupInvitations = UserGroupInvitationRepository; -export const UserNotePinings = db.getRepository(UserNotePining); -export const UserIps = db.getRepository(UserIp); -export const UsedUsernames = db.getRepository(UsedUsername); -export const Followings = FollowingRepository; -export const FollowRequests = FollowRequestRepository; -export const Instances = InstanceRepository; -export const Emojis = EmojiRepository; -export const DriveFiles = DriveFileRepository; -export const DriveFolders = DriveFolderRepository; -export const Notifications = NotificationRepository; -export const Metas = db.getRepository(Meta); -export const Mutings = MutingRepository; -export const RenoteMutings = RenoteMutingRepository; -export const Blockings = BlockingRepository; -export const SwSubscriptions = db.getRepository(SwSubscription); -export const Hashtags = HashtagRepository; -export const AbuseUserReports = AbuseUserReportRepository; -export const RegistrationTickets = db.getRepository(RegistrationTicket); -export const AuthSessions = AuthSessionRepository; -export const AccessTokens = db.getRepository(AccessToken); -export const Signins = SigninRepository; -export const MessagingMessages = MessagingMessageRepository; -export const Pages = PageRepository; -export const PageLikes = PageLikeRepository; -export const GalleryPosts = GalleryPostRepository; -export const GalleryLikes = GalleryLikeRepository; -export const ModerationLogs = ModerationLogRepository; -export const Clips = ClipRepository; -export const ClipNotes = db.getRepository(ClipNote); -export const Antennas = AntennaRepository; -export const AntennaNotes = db.getRepository(AntennaNote); -export const PromoNotes = db.getRepository(PromoNote); -export const PromoReads = db.getRepository(PromoRead); -export const Relays = RelayRepository; -export const MutedNotes = db.getRepository(MutedNote); -export const Channels = ChannelRepository; -export const ChannelFollowings = db.getRepository(ChannelFollowing); -export const ChannelNotePinings = db.getRepository(ChannelNotePining); -export const RegistryItems = db.getRepository(RegistryItem); -export const Webhooks = db.getRepository(Webhook); -export const Ads = db.getRepository(Ad); -export const PasswordResetRequests = db.getRepository(PasswordResetRequest); diff --git a/packages/backend/src/models/repositories/abuse-user-report.ts b/packages/backend/src/models/repositories/abuse-user-report.ts deleted file mode 100644 index 07afef48c4..0000000000 --- a/packages/backend/src/models/repositories/abuse-user-report.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { Users } from "../index.js"; -import { AbuseUserReport } from "@/models/entities/abuse-user-report.js"; -import { awaitAll } from "@/prelude/await-all.js"; - -export const AbuseUserReportRepository = db - .getRepository(AbuseUserReport) - .extend({ - async pack(src: AbuseUserReport["id"] | AbuseUserReport) { - const report = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return await awaitAll({ - id: report.id, - createdAt: report.createdAt.toISOString(), - comment: report.comment, - resolved: report.resolved, - reporterId: report.reporterId, - targetUserId: report.targetUserId, - assigneeId: report.assigneeId, - reporter: Users.pack(report.reporter || report.reporterId, null, { - detail: true, - }), - targetUser: Users.pack(report.targetUser || report.targetUserId, null, { - detail: true, - }), - assignee: report.assigneeId - ? Users.pack(report.assignee || report.assigneeId, null, { - detail: true, - }) - : null, - forwarded: report.forwarded, - }); - }, - - packMany(reports: any[]) { - return Promise.all(reports.map((x) => this.pack(x))); - }, - }); diff --git a/packages/backend/src/models/repositories/antenna.ts b/packages/backend/src/models/repositories/antenna.ts deleted file mode 100644 index c325e25895..0000000000 --- a/packages/backend/src/models/repositories/antenna.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { Antenna } from "@/models/entities/antenna.js"; -import type { Packed } from "@/misc/schema.js"; -import { AntennaNotes, UserGroupJoinings } from "../index.js"; - -export const AntennaRepository = db.getRepository(Antenna).extend({ - async pack(src: Antenna["id"] | Antenna): Promise<Packed<"Antenna">> { - const antenna = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - const hasUnreadNote = - (await AntennaNotes.findOneBy({ antennaId: antenna.id, read: false })) != - null; - const userGroupJoining = antenna.userGroupJoiningId - ? await UserGroupJoinings.findOneBy({ id: antenna.userGroupJoiningId }) - : null; - - return { - id: antenna.id, - createdAt: antenna.createdAt.toISOString(), - name: antenna.name, - keywords: antenna.keywords, - excludeKeywords: antenna.excludeKeywords, - src: antenna.src, - userListId: antenna.userListId, - userGroupId: userGroupJoining ? userGroupJoining.userGroupId : null, - users: antenna.users, - instances: antenna.instances, - caseSensitive: antenna.caseSensitive, - notify: antenna.notify, - withReplies: antenna.withReplies, - withFile: antenna.withFile, - hasUnreadNote, - }; - }, -}); diff --git a/packages/backend/src/models/repositories/app.ts b/packages/backend/src/models/repositories/app.ts deleted file mode 100644 index af3dfb81a1..0000000000 --- a/packages/backend/src/models/repositories/app.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { App } from "@/models/entities/app.js"; -import { AccessTokens } from "../index.js"; -import type { Packed } from "@/misc/schema.js"; -import type { User } from "../entities/user.js"; - -export const AppRepository = db.getRepository(App).extend({ - async pack( - src: App["id"] | App, - me?: { id: User["id"] } | null | undefined, - options?: { - detail?: boolean; - includeSecret?: boolean; - includeProfileImageIds?: boolean; - }, - ): Promise<Packed<"App">> { - const opts = Object.assign( - { - detail: false, - includeSecret: false, - includeProfileImageIds: false, - }, - options, - ); - - const app = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return { - id: app.id, - name: app.name, - callbackUrl: app.callbackUrl, - permission: app.permission, - ...(opts.includeSecret ? { secret: app.secret } : {}), - ...(me - ? { - isAuthorized: await AccessTokens.countBy({ - appId: app.id, - userId: me.id, - }).then((count) => count > 0), - } - : {}), - }; - }, -}); diff --git a/packages/backend/src/models/repositories/auth-session.ts b/packages/backend/src/models/repositories/auth-session.ts deleted file mode 100644 index d3e1d45d6d..0000000000 --- a/packages/backend/src/models/repositories/auth-session.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { Apps } from "../index.js"; -import { AuthSession } from "@/models/entities/auth-session.js"; -import { awaitAll } from "@/prelude/await-all.js"; -import type { User } from "@/models/entities/user.js"; - -export const AuthSessionRepository = db.getRepository(AuthSession).extend({ - async pack( - src: AuthSession["id"] | AuthSession, - me?: { id: User["id"] } | null | undefined, - ) { - const session = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return await awaitAll({ - id: session.id, - app: Apps.pack(session.appId, me), - token: session.token, - }); - }, -}); diff --git a/packages/backend/src/models/repositories/blocking.ts b/packages/backend/src/models/repositories/blocking.ts deleted file mode 100644 index 3dfa74e763..0000000000 --- a/packages/backend/src/models/repositories/blocking.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { Users } from "../index.js"; -import { Blocking } from "@/models/entities/blocking.js"; -import { awaitAll } from "@/prelude/await-all.js"; -import type { Packed } from "@/misc/schema.js"; -import type { User } from "@/models/entities/user.js"; - -export const BlockingRepository = db.getRepository(Blocking).extend({ - async pack( - src: Blocking["id"] | Blocking, - me?: { id: User["id"] } | null | undefined, - ): Promise<Packed<"Blocking">> { - const blocking = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return await awaitAll({ - id: blocking.id, - createdAt: blocking.createdAt.toISOString(), - blockeeId: blocking.blockeeId, - blockee: Users.pack(blocking.blockeeId, me, { - detail: true, - }), - }); - }, - - packMany(blockings: any[], me: { id: User["id"] }) { - return Promise.all(blockings.map((x) => this.pack(x, me))); - }, -}); diff --git a/packages/backend/src/models/repositories/channel.ts b/packages/backend/src/models/repositories/channel.ts deleted file mode 100644 index 7800a65940..0000000000 --- a/packages/backend/src/models/repositories/channel.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { Channel } from "@/models/entities/channel.js"; -import type { Packed } from "@/misc/schema.js"; -import { DriveFiles, ChannelFollowings, NoteUnreads } from "../index.js"; -import type { User } from "@/models/entities/user.js"; - -export const ChannelRepository = db.getRepository(Channel).extend({ - async pack( - src: Channel["id"] | Channel, - me?: { id: User["id"] } | null | undefined, - ): Promise<Packed<"Channel">> { - const channel = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - const meId = me ? me.id : null; - - const banner = channel.bannerId - ? await DriveFiles.findOneBy({ id: channel.bannerId }) - : null; - - const hasUnreadNote = meId - ? (await NoteUnreads.findOneBy({ - noteChannelId: channel.id, - userId: meId, - })) != null - : undefined; - - const following = meId - ? await ChannelFollowings.findOneBy({ - followerId: meId, - followeeId: channel.id, - }) - : null; - - return { - id: channel.id, - createdAt: channel.createdAt.toISOString(), - lastNotedAt: channel.lastNotedAt - ? channel.lastNotedAt.toISOString() - : null, - name: channel.name, - description: channel.description, - userId: channel.userId, - bannerUrl: banner ? DriveFiles.getPublicUrl(banner, false) : null, - usersCount: channel.usersCount, - notesCount: channel.notesCount, - - ...(me - ? { - isFollowing: following != null, - hasUnreadNote, - } - : {}), - }; - }, -}); diff --git a/packages/backend/src/models/repositories/clip.ts b/packages/backend/src/models/repositories/clip.ts deleted file mode 100644 index 0c21691bff..0000000000 --- a/packages/backend/src/models/repositories/clip.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { Clip } from "@/models/entities/clip.js"; -import type { Packed } from "@/misc/schema.js"; -import { Users } from "../index.js"; -import { awaitAll } from "@/prelude/await-all.js"; - -export const ClipRepository = db.getRepository(Clip).extend({ - async pack(src: Clip["id"] | Clip): Promise<Packed<"Clip">> { - const clip = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return await awaitAll({ - id: clip.id, - createdAt: clip.createdAt.toISOString(), - userId: clip.userId, - user: Users.pack(clip.user || clip.userId), - name: clip.name, - description: clip.description, - isPublic: clip.isPublic, - }); - }, - - packMany(clips: Clip[]) { - return Promise.all(clips.map((x) => this.pack(x))); - }, -}); diff --git a/packages/backend/src/models/repositories/drive-file.ts b/packages/backend/src/models/repositories/drive-file.ts deleted file mode 100644 index 3918f7947b..0000000000 --- a/packages/backend/src/models/repositories/drive-file.ts +++ /dev/null @@ -1,224 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { DriveFile } from "@/models/entities/drive-file.js"; -import type { User } from "@/models/entities/user.js"; -import { toPuny } from "@/misc/convert-host.js"; -import { awaitAll, Promiseable } from "@/prelude/await-all.js"; -import type { Packed } from "@/misc/schema.js"; -import config from "@/config/index.js"; -import { query, appendQuery } from "@/prelude/url.js"; -import { Meta } from "@/models/entities/meta.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { Users, DriveFolders } from "../index.js"; -import { deepClone } from "@/misc/clone.js"; - -type PackOptions = { - detail?: boolean; - self?: boolean; - withUser?: boolean; -}; - -export const DriveFileRepository = db.getRepository(DriveFile).extend({ - validateFileName(name: string): boolean { - return ( - name.trim().length > 0 && - name.length <= 200 && - name.indexOf("\\") === -1 && - name.indexOf("/") === -1 && - name.indexOf("..") === -1 - ); - }, - - getPublicProperties(file: DriveFile): DriveFile["properties"] { - if (file.properties.orientation != null) { - const properties = deepClone(file.properties); - if (file.properties.orientation >= 5) { - [properties.width, properties.height] = [ - properties.height, - properties.width, - ]; - } - properties.orientation = undefined; - return properties; - } - - return file.properties; - }, - - getPublicUrl(file: DriveFile, thumbnail = false): string | null { - // リモートかつメディアプロキシ - if ( - file.uri != null && - file.userHost != null && - config.mediaProxy != null - ) { - return appendQuery( - config.mediaProxy, - query({ - url: file.uri, - thumbnail: thumbnail ? "1" : undefined, - }), - ); - } - - // リモートかつ期限切れはローカルプロキシを試みる - if (file.uri != null && file.isLink && config.proxyRemoteFiles) { - const key = thumbnail ? file.thumbnailAccessKey : file.webpublicAccessKey; - - if (key && !key.match("/")) { - // 古いものはここにオブジェクトストレージキーが入ってるので除外 - return `${config.url}/files/${key}`; - } - } - - const isImage = - file.type && - [ - "image/png", - "image/apng", - "image/gif", - "image/jpeg", - "image/webp", - "image/svg+xml", - "image/avif", - ].includes(file.type); - - return thumbnail - ? file.thumbnailUrl || (isImage ? file.webpublicUrl || file.url : null) - : file.webpublicUrl || file.url; - }, - - async calcDriveUsageOf( - user: User["id"] | { id: User["id"] }, - ): Promise<number> { - const id = typeof user === "object" ? user.id : user; - - const { sum } = await this.createQueryBuilder("file") - .where("file.userId = :id", { id: id }) - .andWhere("file.isLink = FALSE") - .select("SUM(file.size)", "sum") - .getRawOne(); - - return parseInt(sum, 10) || 0; - }, - - async calcDriveUsageOfHost(host: string): Promise<number> { - const { sum } = await this.createQueryBuilder("file") - .where("file.userHost = :host", { host: toPuny(host) }) - .andWhere("file.isLink = FALSE") - .select("SUM(file.size)", "sum") - .getRawOne(); - - return parseInt(sum, 10) || 0; - }, - - async calcDriveUsageOfLocal(): Promise<number> { - const { sum } = await this.createQueryBuilder("file") - .where("file.userHost IS NULL") - .andWhere("file.isLink = FALSE") - .select("SUM(file.size)", "sum") - .getRawOne(); - - return parseInt(sum, 10) || 0; - }, - - async calcDriveUsageOfRemote(): Promise<number> { - const { sum } = await this.createQueryBuilder("file") - .where("file.userHost IS NOT NULL") - .andWhere("file.isLink = FALSE") - .select("SUM(file.size)", "sum") - .getRawOne(); - - return parseInt(sum, 10) || 0; - }, - - async pack( - src: DriveFile["id"] | DriveFile, - options?: PackOptions, - ): Promise<Packed<"DriveFile">> { - const opts = Object.assign( - { - detail: false, - self: false, - }, - options, - ); - - const file = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return await awaitAll<Packed<"DriveFile">>({ - id: file.id, - createdAt: file.createdAt.toISOString(), - name: file.name, - type: file.type, - md5: file.md5, - size: file.size, - isSensitive: file.isSensitive, - blurhash: file.blurhash, - properties: opts.self ? file.properties : this.getPublicProperties(file), - url: opts.self ? file.url : this.getPublicUrl(file, false), - thumbnailUrl: this.getPublicUrl(file, true), - comment: file.comment, - folderId: file.folderId, - folder: - opts.detail && file.folderId - ? DriveFolders.pack(file.folderId, { - detail: true, - }) - : null, - userId: opts.withUser ? file.userId : null, - user: opts.withUser && file.userId ? Users.pack(file.userId) : null, - }); - }, - - async packNullable( - src: DriveFile["id"] | DriveFile, - options?: PackOptions, - ): Promise<Packed<"DriveFile"> | null> { - const opts = Object.assign( - { - detail: false, - self: false, - }, - options, - ); - - const file = - typeof src === "object" ? src : await this.findOneBy({ id: src }); - if (file == null) return null; - - return await awaitAll<Packed<"DriveFile">>({ - id: file.id, - createdAt: file.createdAt.toISOString(), - name: file.name, - type: file.type, - md5: file.md5, - size: file.size, - isSensitive: file.isSensitive, - blurhash: file.blurhash, - properties: opts.self ? file.properties : this.getPublicProperties(file), - url: opts.self ? file.url : this.getPublicUrl(file, false), - thumbnailUrl: this.getPublicUrl(file, true), - comment: file.comment, - folderId: file.folderId, - folder: - opts.detail && file.folderId - ? DriveFolders.pack(file.folderId, { - detail: true, - }) - : null, - userId: opts.withUser ? file.userId : null, - user: opts.withUser && file.userId ? Users.pack(file.userId) : null, - }); - }, - - async packMany( - files: (DriveFile["id"] | DriveFile)[], - options?: PackOptions, - ): Promise<Packed<"DriveFile">[]> { - const items = await Promise.all( - files.map((f) => this.packNullable(f, options)), - ); - return items.filter((x): x is Packed<"DriveFile"> => x != null); - }, -}); diff --git a/packages/backend/src/models/repositories/drive-folder.ts b/packages/backend/src/models/repositories/drive-folder.ts deleted file mode 100644 index 9823561d0b..0000000000 --- a/packages/backend/src/models/repositories/drive-folder.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { DriveFolders, DriveFiles } from "../index.js"; -import { DriveFolder } from "@/models/entities/drive-folder.js"; -import { awaitAll } from "@/prelude/await-all.js"; -import type { Packed } from "@/misc/schema.js"; - -export const DriveFolderRepository = db.getRepository(DriveFolder).extend({ - async pack( - src: DriveFolder["id"] | DriveFolder, - options?: { - detail: boolean; - }, - ): Promise<Packed<"DriveFolder">> { - const opts = Object.assign( - { - detail: false, - }, - options, - ); - - const folder = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return await awaitAll({ - id: folder.id, - createdAt: folder.createdAt.toISOString(), - name: folder.name, - parentId: folder.parentId, - - ...(opts.detail - ? { - foldersCount: DriveFolders.countBy({ - parentId: folder.id, - }), - filesCount: DriveFiles.countBy({ - folderId: folder.id, - }), - - ...(folder.parentId - ? { - parent: this.pack(folder.parentId, { - detail: true, - }), - } - : {}), - } - : {}), - }); - }, -}); diff --git a/packages/backend/src/models/repositories/emoji.ts b/packages/backend/src/models/repositories/emoji.ts deleted file mode 100644 index 6eabfe9558..0000000000 --- a/packages/backend/src/models/repositories/emoji.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { Emoji } from "@/models/entities/emoji.js"; -import type { Packed } from "@/misc/schema.js"; - -export const EmojiRepository = db.getRepository(Emoji).extend({ - async pack(src: Emoji["id"] | Emoji): Promise<Packed<"Emoji">> { - const emoji = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return { - id: emoji.id, - aliases: emoji.aliases, - name: emoji.name, - category: emoji.category, - host: emoji.host, - // || emoji.originalUrl してるのは後方互換性のため - url: emoji.publicUrl || emoji.originalUrl, - license: emoji.license, - }; - }, - - packMany(emojis: any[]) { - return Promise.all(emojis.map((x) => this.pack(x))); - }, -}); diff --git a/packages/backend/src/models/repositories/follow-request.ts b/packages/backend/src/models/repositories/follow-request.ts deleted file mode 100644 index cef6ea7228..0000000000 --- a/packages/backend/src/models/repositories/follow-request.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { FollowRequest } from "@/models/entities/follow-request.js"; -import { Users } from "../index.js"; -import type { User } from "@/models/entities/user.js"; - -export const FollowRequestRepository = db.getRepository(FollowRequest).extend({ - async pack( - src: FollowRequest["id"] | FollowRequest, - me?: { id: User["id"] } | null | undefined, - ) { - const request = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return { - id: request.id, - follower: await Users.pack(request.followerId, me), - followee: await Users.pack(request.followeeId, me), - }; - }, -}); diff --git a/packages/backend/src/models/repositories/following.ts b/packages/backend/src/models/repositories/following.ts deleted file mode 100644 index b102365e09..0000000000 --- a/packages/backend/src/models/repositories/following.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { Users } from "../index.js"; -import { Following } from "@/models/entities/following.js"; -import { awaitAll } from "@/prelude/await-all.js"; -import type { Packed } from "@/misc/schema.js"; -import type { User } from "@/models/entities/user.js"; - -type LocalFollowerFollowing = Following & { - followerHost: null; - followerInbox: null; - followerSharedInbox: null; -}; - -type RemoteFollowerFollowing = Following & { - followerHost: string; - followerInbox: string; - followerSharedInbox: string; -}; - -type LocalFolloweeFollowing = Following & { - followeeHost: null; - followeeInbox: null; - followeeSharedInbox: null; -}; - -type RemoteFolloweeFollowing = Following & { - followeeHost: string; - followeeInbox: string; - followeeSharedInbox: string; -}; - -export const FollowingRepository = db.getRepository(Following).extend({ - isLocalFollower(following: Following): following is LocalFollowerFollowing { - return following.followerHost == null; - }, - - isRemoteFollower(following: Following): following is RemoteFollowerFollowing { - return following.followerHost != null; - }, - - isLocalFollowee(following: Following): following is LocalFolloweeFollowing { - return following.followeeHost == null; - }, - - isRemoteFollowee(following: Following): following is RemoteFolloweeFollowing { - return following.followeeHost != null; - }, - - async pack( - src: Following["id"] | Following, - me?: { id: User["id"] } | null | undefined, - opts?: { - populateFollowee?: boolean; - populateFollower?: boolean; - }, - ): Promise<Packed<"Following">> { - const following = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - if (opts == null) opts = {}; - - return await awaitAll({ - id: following.id, - createdAt: following.createdAt.toISOString(), - followeeId: following.followeeId, - followerId: following.followerId, - followee: opts.populateFollowee - ? Users.pack(following.followee || following.followeeId, me, { - detail: true, - }) - : undefined, - follower: opts.populateFollower - ? Users.pack(following.follower || following.followerId, me, { - detail: true, - }) - : undefined, - }); - }, - - packMany( - followings: any[], - me?: { id: User["id"] } | null | undefined, - opts?: { - populateFollowee?: boolean; - populateFollower?: boolean; - }, - ) { - return Promise.all(followings.map((x) => this.pack(x, me, opts))); - }, -}); diff --git a/packages/backend/src/models/repositories/gallery-like.ts b/packages/backend/src/models/repositories/gallery-like.ts deleted file mode 100644 index c8920d1ee6..0000000000 --- a/packages/backend/src/models/repositories/gallery-like.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { GalleryLike } from "@/models/entities/gallery-like.js"; -import { GalleryPosts } from "../index.js"; - -export const GalleryLikeRepository = db.getRepository(GalleryLike).extend({ - async pack(src: GalleryLike["id"] | GalleryLike, me?: any) { - const like = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return { - id: like.id, - post: await GalleryPosts.pack(like.post || like.postId, me), - }; - }, - - packMany(likes: any[], me: any) { - return Promise.all(likes.map((x) => this.pack(x, me))); - }, -}); diff --git a/packages/backend/src/models/repositories/gallery-post.ts b/packages/backend/src/models/repositories/gallery-post.ts deleted file mode 100644 index b4206b0bf4..0000000000 --- a/packages/backend/src/models/repositories/gallery-post.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { GalleryPost } from "@/models/entities/gallery-post.js"; -import type { Packed } from "@/misc/schema.js"; -import { Users, DriveFiles, GalleryLikes } from "../index.js"; -import { awaitAll } from "@/prelude/await-all.js"; -import type { User } from "@/models/entities/user.js"; - -export const GalleryPostRepository = db.getRepository(GalleryPost).extend({ - async pack( - src: GalleryPost["id"] | GalleryPost, - me?: { id: User["id"] } | null | undefined, - ): Promise<Packed<"GalleryPost">> { - const meId = me ? me.id : null; - const post = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return await awaitAll({ - id: post.id, - createdAt: post.createdAt.toISOString(), - updatedAt: post.updatedAt.toISOString(), - userId: post.userId, - user: Users.pack(post.user || post.userId, me), - title: post.title, - description: post.description, - fileIds: post.fileIds, - files: DriveFiles.packMany(post.fileIds), - tags: post.tags.length > 0 ? post.tags : undefined, - isSensitive: post.isSensitive, - likedCount: post.likedCount, - isLiked: meId - ? await GalleryLikes.findOneBy({ postId: post.id, userId: meId }).then( - (x) => x != null, - ) - : undefined, - }); - }, - - packMany(posts: GalleryPost[], me?: { id: User["id"] } | null | undefined) { - return Promise.all(posts.map((x) => this.pack(x, me))); - }, -}); diff --git a/packages/backend/src/models/repositories/hashtag.ts b/packages/backend/src/models/repositories/hashtag.ts deleted file mode 100644 index 7bd76c1c70..0000000000 --- a/packages/backend/src/models/repositories/hashtag.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { Hashtag } from "@/models/entities/hashtag.js"; -import type { Packed } from "@/misc/schema.js"; - -export const HashtagRepository = db.getRepository(Hashtag).extend({ - async pack(src: Hashtag): Promise<Packed<"Hashtag">> { - return { - tag: src.name, - mentionedUsersCount: src.mentionedUsersCount, - mentionedLocalUsersCount: src.mentionedLocalUsersCount, - mentionedRemoteUsersCount: src.mentionedRemoteUsersCount, - attachedUsersCount: src.attachedUsersCount, - attachedLocalUsersCount: src.attachedLocalUsersCount, - attachedRemoteUsersCount: src.attachedRemoteUsersCount, - }; - }, - - packMany(hashtags: Hashtag[]) { - return Promise.all(hashtags.map((x) => this.pack(x))); - }, -}); diff --git a/packages/backend/src/models/repositories/instance.ts b/packages/backend/src/models/repositories/instance.ts deleted file mode 100644 index fb4498911a..0000000000 --- a/packages/backend/src/models/repositories/instance.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { Instance } from "@/models/entities/instance.js"; -import type { Packed } from "@/misc/schema.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { shouldBlockInstance } from "@/misc/should-block-instance.js"; - -export const InstanceRepository = db.getRepository(Instance).extend({ - async pack(instance: Instance): Promise<Packed<"FederationInstance">> { - const meta = await fetchMeta(); - return { - id: instance.id, - caughtAt: instance.caughtAt.toISOString(), - host: instance.host, - usersCount: instance.usersCount, - notesCount: instance.notesCount, - followingCount: instance.followingCount, - followersCount: instance.followersCount, - latestRequestSentAt: instance.latestRequestSentAt - ? instance.latestRequestSentAt.toISOString() - : null, - lastCommunicatedAt: instance.lastCommunicatedAt.toISOString(), - isNotResponding: instance.isNotResponding, - isSuspended: instance.isSuspended, - isBlocked: await shouldBlockInstance(instance.host), - softwareName: instance.softwareName, - softwareVersion: instance.softwareVersion, - openRegistrations: instance.openRegistrations, - name: instance.name, - description: instance.description, - maintainerName: instance.maintainerName, - maintainerEmail: instance.maintainerEmail, - iconUrl: instance.iconUrl, - faviconUrl: instance.faviconUrl, - themeColor: instance.themeColor, - infoUpdatedAt: instance.infoUpdatedAt - ? instance.infoUpdatedAt.toISOString() - : null, - }; - }, - - packMany(instances: Instance[]) { - return Promise.all(instances.map((x) => this.pack(x))); - }, -}); diff --git a/packages/backend/src/models/repositories/messaging-message.ts b/packages/backend/src/models/repositories/messaging-message.ts deleted file mode 100644 index 6c0987bf08..0000000000 --- a/packages/backend/src/models/repositories/messaging-message.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { MessagingMessage } from "@/models/entities/messaging-message.js"; -import { Users, DriveFiles, UserGroups } from "../index.js"; -import type { Packed } from "@/misc/schema.js"; -import type { User } from "@/models/entities/user.js"; - -export const MessagingMessageRepository = db - .getRepository(MessagingMessage) - .extend({ - async pack( - src: MessagingMessage["id"] | MessagingMessage, - me?: { id: User["id"] } | null | undefined, - options?: { - populateRecipient?: boolean; - populateGroup?: boolean; - }, - ): Promise<Packed<"MessagingMessage">> { - const opts = options || { - populateRecipient: true, - populateGroup: true, - }; - - const message = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return { - id: message.id, - createdAt: message.createdAt.toISOString(), - text: message.text, - userId: message.userId, - user: await Users.pack(message.user || message.userId, me), - recipientId: message.recipientId, - recipient: - message.recipientId && opts.populateRecipient - ? await Users.pack(message.recipient || message.recipientId, me) - : undefined, - groupId: message.groupId, - group: - message.groupId && opts.populateGroup - ? await UserGroups.pack(message.group || message.groupId) - : undefined, - fileId: message.fileId, - file: message.fileId ? await DriveFiles.pack(message.fileId) : null, - isRead: message.isRead, - reads: message.reads, - }; - }, - }); diff --git a/packages/backend/src/models/repositories/moderation-logs.ts b/packages/backend/src/models/repositories/moderation-logs.ts deleted file mode 100644 index 3858b9509b..0000000000 --- a/packages/backend/src/models/repositories/moderation-logs.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { Users } from "../index.js"; -import { ModerationLog } from "@/models/entities/moderation-log.js"; -import { awaitAll } from "@/prelude/await-all.js"; - -export const ModerationLogRepository = db.getRepository(ModerationLog).extend({ - async pack(src: ModerationLog["id"] | ModerationLog) { - const log = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return await awaitAll({ - id: log.id, - createdAt: log.createdAt.toISOString(), - type: log.type, - info: log.info, - userId: log.userId, - user: Users.pack(log.user || log.userId, null, { - detail: true, - }), - }); - }, - - packMany(reports: any[]) { - return Promise.all(reports.map((x) => this.pack(x))); - }, -}); diff --git a/packages/backend/src/models/repositories/muting.ts b/packages/backend/src/models/repositories/muting.ts deleted file mode 100644 index 4d0201d5a0..0000000000 --- a/packages/backend/src/models/repositories/muting.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { Users } from "../index.js"; -import { Muting } from "@/models/entities/muting.js"; -import { awaitAll } from "@/prelude/await-all.js"; -import type { Packed } from "@/misc/schema.js"; -import type { User } from "@/models/entities/user.js"; - -export const MutingRepository = db.getRepository(Muting).extend({ - async pack( - src: Muting["id"] | Muting, - me?: { id: User["id"] } | null | undefined, - ): Promise<Packed<"Muting">> { - const muting = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return await awaitAll({ - id: muting.id, - createdAt: muting.createdAt.toISOString(), - expiresAt: muting.expiresAt ? muting.expiresAt.toISOString() : null, - muteeId: muting.muteeId, - mutee: Users.pack(muting.muteeId, me, { - detail: true, - }), - }); - }, - - packMany(mutings: any[], me: { id: User["id"] }) { - return Promise.all(mutings.map((x) => this.pack(x, me))); - }, -}); diff --git a/packages/backend/src/models/repositories/note-favorite.ts b/packages/backend/src/models/repositories/note-favorite.ts deleted file mode 100644 index ba43e3c3b4..0000000000 --- a/packages/backend/src/models/repositories/note-favorite.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { NoteFavorite } from "@/models/entities/note-favorite.js"; -import { Notes } from "../index.js"; -import type { User } from "@/models/entities/user.js"; - -export const NoteFavoriteRepository = db.getRepository(NoteFavorite).extend({ - async pack( - src: NoteFavorite["id"] | NoteFavorite, - me?: { id: User["id"] } | null | undefined, - ) { - const favorite = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return { - id: favorite.id, - createdAt: favorite.createdAt.toISOString(), - noteId: favorite.noteId, - // may throw error - note: await Notes.pack(favorite.note || favorite.noteId, me), - }; - }, - - packMany(favorites: any[], me: { id: User["id"] }) { - return Promise.allSettled(favorites.map((x) => this.pack(x, me))).then( - (promises) => - promises.flatMap((result) => - result.status === "fulfilled" ? [result.value] : [], - ), - ); - }, -}); diff --git a/packages/backend/src/models/repositories/note-reaction.ts b/packages/backend/src/models/repositories/note-reaction.ts deleted file mode 100644 index 6d1dfbd6fd..0000000000 --- a/packages/backend/src/models/repositories/note-reaction.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { NoteReaction } from "@/models/entities/note-reaction.js"; -import { Notes, Users } from "../index.js"; -import type { Packed } from "@/misc/schema.js"; -import { convertLegacyReaction } from "@/misc/reaction-lib.js"; -import type { User } from "@/models/entities/user.js"; - -export const NoteReactionRepository = db.getRepository(NoteReaction).extend({ - async pack( - src: NoteReaction["id"] | NoteReaction, - me?: { id: User["id"] } | null | undefined, - options?: { - withNote: boolean; - }, - ): Promise<Packed<"NoteReaction">> { - const opts = Object.assign( - { - withNote: false, - }, - options, - ); - - const reaction = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return { - id: reaction.id, - createdAt: reaction.createdAt.toISOString(), - user: await Users.pack(reaction.user ?? reaction.userId, me), - type: convertLegacyReaction(reaction.reaction), - ...(opts.withNote - ? { - // may throw error - note: await Notes.pack(reaction.note ?? reaction.noteId, me), - } - : {}), - }; - }, - - async packMany( - src: NoteReaction[], - me?: { id: User["id"] } | null | undefined, - options?: { - withNote: booleam; - }, - ): Promise<Packed<"NoteReaction">[]> { - const reactions = await Promise.allSettled( - src.map((reaction) => this.pack(reaction, me, options)), - ); - - // filter out rejected promises, only keep fulfilled values - return reactions.flatMap((result) => - result.status === "fulfilled" ? [result.value] : [], - ); - }, -}); diff --git a/packages/backend/src/models/repositories/note.ts b/packages/backend/src/models/repositories/note.ts deleted file mode 100644 index 5e56a817bc..0000000000 --- a/packages/backend/src/models/repositories/note.ts +++ /dev/null @@ -1,334 +0,0 @@ -import { In } from "typeorm"; -import * as mfm from "mfm-js"; -import { Note } from "@/models/entities/note.js"; -import type { User } from "@/models/entities/user.js"; -import { - Users, - PollVotes, - DriveFiles, - NoteReactions, - Followings, - Polls, - Channels, -} from "../index.js"; -import type { Packed } from "@/misc/schema.js"; -import { nyaize } from "@/misc/nyaize.js"; -import { awaitAll } from "@/prelude/await-all.js"; -import { - convertLegacyReaction, - convertLegacyReactions, - decodeReaction, -} from "@/misc/reaction-lib.js"; -import type { NoteReaction } from "@/models/entities/note-reaction.js"; -import { - aggregateNoteEmojis, - populateEmojis, - prefetchEmojis, -} from "@/misc/populate-emojis.js"; -import { db } from "@/db/postgre.js"; -import { IdentifiableError } from "@/misc/identifiable-error.js"; - -async function populatePoll(note: Note, meId: User["id"] | null) { - const poll = await Polls.findOneByOrFail({ noteId: note.id }); - const choices = poll.choices.map((c) => ({ - text: c, - votes: poll.votes[poll.choices.indexOf(c)], - isVoted: false, - })); - - if (meId) { - if (poll.multiple) { - const votes = await PollVotes.findBy({ - userId: meId, - noteId: note.id, - }); - - const myChoices = votes.map((v) => v.choice); - for (const myChoice of myChoices) { - choices[myChoice].isVoted = true; - } - } else { - const vote = await PollVotes.findOneBy({ - userId: meId, - noteId: note.id, - }); - - if (vote) { - choices[vote.choice].isVoted = true; - } - } - } - - return { - multiple: poll.multiple, - expiresAt: poll.expiresAt, - choices, - }; -} - -async function populateMyReaction( - note: Note, - meId: User["id"], - _hint_?: { - myReactions: Map<Note["id"], NoteReaction | null>; - }, -) { - if (_hint_?.myReactions) { - const reaction = _hint_.myReactions.get(note.id); - if (reaction) { - return convertLegacyReaction(reaction.reaction); - } else if (reaction === null) { - return undefined; - } - // 実装上抜けがあるだけかもしれないので、「ヒントに含まれてなかったら(=undefinedなら)return」のようにはしない - } - - const reaction = await NoteReactions.findOneBy({ - userId: meId, - noteId: note.id, - }); - - if (reaction) { - return convertLegacyReaction(reaction.reaction); - } - - return undefined; -} - -export const NoteRepository = db.getRepository(Note).extend({ - async isVisibleForMe(note: Note, meId: User["id"] | null): Promise<boolean> { - // This code must always be synchronized with the checks in generateVisibilityQuery. - // visibility が specified かつ自分が指定されていなかったら非表示 - if (note.visibility === "specified") { - if (meId == null) { - return false; - } else if (meId === note.userId) { - return true; - } else { - // 指定されているかどうか - return note.visibleUserIds.some((id: any) => meId === id); - } - } - - // visibility が followers かつ自分が投稿者のフォロワーでなかったら非表示 - if (note.visibility === "followers") { - if (meId == null) { - return false; - } else if (meId === note.userId) { - return true; - } else if (note.reply && meId === note.reply.userId) { - // 自分の投稿に対するリプライ - return true; - } else if (note.mentions?.some((id) => meId === id)) { - // 自分へのメンション - return true; - } else { - // フォロワーかどうか - const [following, user] = await Promise.all([ - Followings.count({ - where: { - followeeId: note.userId, - followerId: meId, - }, - take: 1, - }), - Users.findOneByOrFail({ id: meId }), - ]); - - /* If we know the following, everyhting is fine. - - But if we do not know the following, it might be that both the - author of the note and the author of the like are remote users, - in which case we can never know the following. Instead we have - to assume that the users are following each other. - */ - return following > 0 || (note.userHost != null && user.host != null); - } - } - - return true; - }, - - async pack( - src: Note["id"] | Note, - me?: { id: User["id"] } | null | undefined, - options?: { - detail?: boolean; - _hint_?: { - myReactions: Map<Note["id"], NoteReaction | null>; - }; - }, - ): Promise<Packed<"Note">> { - const opts = Object.assign( - { - detail: true, - }, - options, - ); - - const meId = me ? me.id : null; - const note = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - const host = note.userHost; - - if (!(await this.isVisibleForMe(note, meId))) { - throw new IdentifiableError( - "9725d0ce-ba28-4dde-95a7-2cbb2c15de24", - "No such note.", - ); - } - - let text = note.text; - - if (note.name && (note.url ?? note.uri)) { - text = `【${note.name}】\n${(note.text || "").trim()}\n\n${ - note.url ?? note.uri - }`; - } - - const channel = note.channelId - ? note.channel - ? note.channel - : await Channels.findOneBy({ id: note.channelId }) - : null; - - const reactionEmojiNames = Object.keys(note.reactions) - .filter((x) => x?.startsWith(":")) - .map((x) => decodeReaction(x).reaction) - .map((x) => x.replace(/:/g, "")); - - const noteEmoji = await populateEmojis( - note.emojis.concat(reactionEmojiNames), - host, - ); - const reactionEmoji = await populateEmojis(reactionEmojiNames, host); - const packed: Packed<"Note"> = await awaitAll({ - id: note.id, - createdAt: note.createdAt.toISOString(), - userId: note.userId, - user: Users.pack(note.user ?? note.userId, me, { - detail: false, - }), - text: text, - cw: note.cw, - visibility: note.visibility, - localOnly: note.localOnly || undefined, - visibleUserIds: - note.visibility === "specified" ? note.visibleUserIds : undefined, - renoteCount: note.renoteCount, - repliesCount: note.repliesCount, - reactions: convertLegacyReactions(note.reactions), - reactionEmojis: reactionEmoji, - emojis: noteEmoji, - tags: note.tags.length > 0 ? note.tags : undefined, - fileIds: note.fileIds, - files: DriveFiles.packMany(note.fileIds), - replyId: note.replyId, - renoteId: note.renoteId, - channelId: note.channelId || undefined, - channel: channel - ? { - id: channel.id, - name: channel.name, - } - : undefined, - mentions: note.mentions.length > 0 ? note.mentions : undefined, - uri: note.uri || undefined, - url: note.url || undefined, - - ...(opts.detail - ? { - reply: note.replyId - ? this.pack(note.reply || note.replyId, me, { - detail: false, - _hint_: options?._hint_, - }) - : undefined, - - renote: note.renoteId - ? this.pack(note.renote || note.renoteId, me, { - detail: true, - _hint_: options?._hint_, - }) - : undefined, - - poll: note.hasPoll ? populatePoll(note, meId) : undefined, - - ...(meId - ? { - myReaction: populateMyReaction(note, meId, options?._hint_), - } - : {}), - } - : {}), - }); - - if (packed.user.isCat && packed.user.speakAsCat && packed.text) { - const tokens = packed.text ? mfm.parse(packed.text) : []; - function nyaizeNode(node: mfm.MfmNode) { - if (node.type === "quote") return; - if (node.type === "text") node.props.text = nyaize(node.props.text); - - if (node.children) { - for (const child of node.children) { - nyaizeNode(child); - } - } - } - - for (const node of tokens) nyaizeNode(node); - - packed.text = mfm.toString(tokens); - } - - return packed; - }, - - async packMany( - notes: Note[], - me?: { id: User["id"] } | null | undefined, - options?: { - detail?: boolean; - }, - ) { - if (notes.length === 0) return []; - - const meId = me ? me.id : null; - const myReactionsMap = new Map<Note["id"], NoteReaction | null>(); - if (meId) { - const renoteIds = notes - .filter((n) => n.renoteId != null) - .map((n) => n.renoteId!); - const targets = [...notes.map((n) => n.id), ...renoteIds]; - const myReactions = await NoteReactions.findBy({ - userId: meId, - noteId: In(targets), - }); - - for (const target of targets) { - myReactionsMap.set( - target, - myReactions.find((reaction) => reaction.noteId === target) || null, - ); - } - } - - await prefetchEmojis(aggregateNoteEmojis(notes)); - - const promises = await Promise.allSettled( - notes.map((n) => - this.pack(n, me, { - ...options, - _hint_: { - myReactions: myReactionsMap, - }, - }), - ), - ); - - // filter out rejected promises, only keep fulfilled values - return promises.flatMap((result) => - result.status === "fulfilled" ? [result.value] : [], - ); - }, -}); diff --git a/packages/backend/src/models/repositories/notification.ts b/packages/backend/src/models/repositories/notification.ts deleted file mode 100644 index 1538e67d86..0000000000 --- a/packages/backend/src/models/repositories/notification.ts +++ /dev/null @@ -1,185 +0,0 @@ -import { In, Repository } from "typeorm"; -import { Notification } from "@/models/entities/notification.js"; -import { awaitAll } from "@/prelude/await-all.js"; -import type { Packed } from "@/misc/schema.js"; -import type { Note } from "@/models/entities/note.js"; -import type { NoteReaction } from "@/models/entities/note-reaction.js"; -import type { User } from "@/models/entities/user.js"; -import { aggregateNoteEmojis, prefetchEmojis } from "@/misc/populate-emojis.js"; -import { notificationTypes } from "@/types.js"; -import { db } from "@/db/postgre.js"; -import { - Users, - Notes, - UserGroupInvitations, - AccessTokens, - NoteReactions, -} from "../index.js"; - -export const NotificationRepository = db.getRepository(Notification).extend({ - async pack( - src: Notification["id"] | Notification, - options: { - _hintForEachNotes_?: { - myReactions: Map<Note["id"], NoteReaction | null>; - }; - }, - ): Promise<Packed<"Notification">> { - const notification = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - const token = notification.appAccessTokenId - ? await AccessTokens.findOneByOrFail({ - id: notification.appAccessTokenId, - }) - : null; - - return await awaitAll({ - id: notification.id, - createdAt: notification.createdAt.toISOString(), - type: notification.type, - isRead: notification.isRead, - userId: notification.notifierId, - user: notification.notifierId - ? Users.pack(notification.notifier || notification.notifierId) - : null, - ...(notification.type === "mention" - ? { - note: Notes.pack( - notification.note || notification.noteId!, - { id: notification.notifieeId }, - { - detail: true, - _hint_: options._hintForEachNotes_, - }, - ), - } - : {}), - ...(notification.type === "reply" - ? { - note: Notes.pack( - notification.note || notification.noteId!, - { id: notification.notifieeId }, - { - detail: true, - _hint_: options._hintForEachNotes_, - }, - ), - } - : {}), - ...(notification.type === "renote" - ? { - note: Notes.pack( - notification.note || notification.noteId!, - { id: notification.notifieeId }, - { - detail: true, - _hint_: options._hintForEachNotes_, - }, - ), - } - : {}), - ...(notification.type === "quote" - ? { - note: Notes.pack( - notification.note || notification.noteId!, - { id: notification.notifieeId }, - { - detail: true, - _hint_: options._hintForEachNotes_, - }, - ), - } - : {}), - ...(notification.type === "reaction" - ? { - note: Notes.pack( - notification.note || notification.noteId!, - { id: notification.notifieeId }, - { - detail: true, - _hint_: options._hintForEachNotes_, - }, - ), - reaction: notification.reaction, - } - : {}), - ...(notification.type === "pollVote" - ? { - note: Notes.pack( - notification.note || notification.noteId!, - { id: notification.notifieeId }, - { - detail: true, - _hint_: options._hintForEachNotes_, - }, - ), - choice: notification.choice, - } - : {}), - ...(notification.type === "pollEnded" - ? { - note: Notes.pack( - notification.note || notification.noteId!, - { id: notification.notifieeId }, - { - detail: true, - _hint_: options._hintForEachNotes_, - }, - ), - } - : {}), - ...(notification.type === "groupInvited" - ? { - invitation: UserGroupInvitations.pack( - notification.userGroupInvitationId!, - ), - } - : {}), - ...(notification.type === "app" - ? { - body: notification.customBody, - header: notification.customHeader || token?.name, - icon: notification.customIcon || token?.iconUrl, - } - : {}), - }); - }, - - async packMany(notifications: Notification[], meId: User["id"]) { - if (notifications.length === 0) return []; - - const notes = notifications - .filter((x) => x.note != null) - .map((x) => x.note!); - const noteIds = notes.map((n) => n.id); - const myReactionsMap = new Map<Note["id"], NoteReaction | null>(); - const renoteIds = notes - .filter((n) => n.renoteId != null) - .map((n) => n.renoteId!); - const targets = [...noteIds, ...renoteIds]; - const myReactions = await NoteReactions.findBy({ - userId: meId, - noteId: In(targets), - }); - - for (const target of targets) { - myReactionsMap.set( - target, - myReactions.find((reaction) => reaction.noteId === target) || null, - ); - } - - await prefetchEmojis(aggregateNoteEmojis(notes)); - - const results = await Promise.all( - notifications.map((x) => - this.pack(x, { - _hintForEachNotes_: { - myReactions: myReactionsMap, - }, - }).catch((e) => null), - ), - ); - return results.filter((x) => x != null); - }, -}); diff --git a/packages/backend/src/models/repositories/page-like.ts b/packages/backend/src/models/repositories/page-like.ts deleted file mode 100644 index f78ef81b02..0000000000 --- a/packages/backend/src/models/repositories/page-like.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { PageLike } from "@/models/entities/page-like.js"; -import type { User } from "@/models/entities/user.js"; -import { Pages } from "../index.js"; - -export const PageLikeRepository = db.getRepository(PageLike).extend({ - async pack( - src: PageLike["id"] | PageLike, - me?: { id: User["id"] } | null | undefined, - ) { - const like = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return { - id: like.id, - page: await Pages.pack(like.page || like.pageId, me), - }; - }, - - packMany(likes: PageLike[], me: { id: User["id"] }) { - return Promise.all(likes.map((x) => this.pack(x, me))); - }, -}); diff --git a/packages/backend/src/models/repositories/page.ts b/packages/backend/src/models/repositories/page.ts deleted file mode 100644 index d9241c3629..0000000000 --- a/packages/backend/src/models/repositories/page.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { Page } from "@/models/entities/page.js"; -import type { Packed } from "@/misc/schema.js"; -import { awaitAll } from "@/prelude/await-all.js"; -import type { DriveFile } from "@/models/entities/drive-file.js"; -import type { User } from "@/models/entities/user.js"; -import { Users, DriveFiles, PageLikes } from "../index.js"; - -export const PageRepository = db.getRepository(Page).extend({ - async pack( - src: Page["id"] | Page, - me?: { id: User["id"] } | null | undefined, - ): Promise<Packed<"Page">> { - const meId = me ? me.id : null; - const page = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - const attachedFiles: Promise<DriveFile | null>[] = []; - const collectFile = (xs: any[]) => { - for (const x of xs) { - if (x.type === "image") { - attachedFiles.push( - DriveFiles.findOneBy({ - id: x.fileId, - userId: page.userId, - }), - ); - } - if (x.children) { - collectFile(x.children); - } - } - }; - collectFile(page.content); - - // 後方互換性のため - let migrated = false; - const migrate = (xs: any[]) => { - for (const x of xs) { - if (x.type === "input") { - if (x.inputType === "text") { - x.type = "textInput"; - } - if (x.inputType === "number") { - x.type = "numberInput"; - if (x.default) x.default = parseInt(x.default, 10); - } - migrated = true; - } - if (x.children) { - migrate(x.children); - } - } - }; - migrate(page.content); - if (migrated) { - this.update(page.id, { - content: page.content, - }); - } - - return await awaitAll({ - id: page.id, - createdAt: page.createdAt.toISOString(), - updatedAt: page.updatedAt.toISOString(), - userId: page.userId, - user: Users.pack(page.user || page.userId, me), // { detail: true } すると無限ループするので注意 - content: page.content, - variables: page.variables, - title: page.title, - isPublic: page.isPublic, - name: page.name, - summary: page.summary, - hideTitleWhenPinned: page.hideTitleWhenPinned, - alignCenter: page.alignCenter, - font: page.font, - script: page.script, - eyeCatchingImageId: page.eyeCatchingImageId, - eyeCatchingImage: page.eyeCatchingImageId - ? await DriveFiles.pack(page.eyeCatchingImageId) - : null, - attachedFiles: DriveFiles.packMany( - ( - await Promise.all(attachedFiles) - ).filter((x): x is DriveFile => x != null), - ), - likedCount: page.likedCount, - isLiked: meId - ? await PageLikes.findOneBy({ pageId: page.id, userId: meId }).then( - (x) => x != null, - ) - : undefined, - }); - }, - - packMany(pages: Page[], me?: { id: User["id"] } | null | undefined) { - return Promise.all(pages.map((x) => this.pack(x, me))); - }, -}); diff --git a/packages/backend/src/models/repositories/relay.ts b/packages/backend/src/models/repositories/relay.ts deleted file mode 100644 index 633861496a..0000000000 --- a/packages/backend/src/models/repositories/relay.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { Relay } from "@/models/entities/relay.js"; - -export const RelayRepository = db.getRepository(Relay).extend({}); diff --git a/packages/backend/src/models/repositories/renote-muting.ts b/packages/backend/src/models/repositories/renote-muting.ts deleted file mode 100644 index 18fd343a05..0000000000 --- a/packages/backend/src/models/repositories/renote-muting.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { Packed } from "@/misc/schema.js"; -import { RenoteMuting } from "@/models/entities/renote-muting.js"; -import { User } from "@/models/entities/user.js"; -import { awaitAll } from "@/prelude/await-all.js"; -import { Users } from "../index.js"; - -export const RenoteMutingRepository = db.getRepository(RenoteMuting).extend({ - async pack( - src: RenoteMuting["id"] | RenoteMuting, - me?: { id: User["id"] } | null | undefined, - ): Promise<Packed<"RenoteMuting">> { - const muting = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return await awaitAll({ - id: muting.id, - createdAt: muting.createdAt.toISOString(), - muteeId: muting.muteeId, - mutee: Users.pack(muting.muteeId, me, { - detail: true, - }), - }); - }, - - packMany(mutings: any[], me: { id: User["id"] }) { - return Promise.all(mutings.map((x) => this.pack(x, me))); - }, -}); diff --git a/packages/backend/src/models/repositories/signin.ts b/packages/backend/src/models/repositories/signin.ts deleted file mode 100644 index 06cf2c2108..0000000000 --- a/packages/backend/src/models/repositories/signin.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { Signin } from "@/models/entities/signin.js"; - -export const SigninRepository = db.getRepository(Signin).extend({ - async pack(src: Signin) { - return src; - }, -}); diff --git a/packages/backend/src/models/repositories/user-group-invitation.ts b/packages/backend/src/models/repositories/user-group-invitation.ts deleted file mode 100644 index 920fb9ba29..0000000000 --- a/packages/backend/src/models/repositories/user-group-invitation.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { UserGroupInvitation } from "@/models/entities/user-group-invitation.js"; -import { UserGroups } from "../index.js"; - -export const UserGroupInvitationRepository = db - .getRepository(UserGroupInvitation) - .extend({ - async pack(src: UserGroupInvitation["id"] | UserGroupInvitation) { - const invitation = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - return { - id: invitation.id, - group: await UserGroups.pack( - invitation.userGroup || invitation.userGroupId, - ), - }; - }, - - packMany(invitations: any[]) { - return Promise.all(invitations.map((x) => this.pack(x))); - }, - }); diff --git a/packages/backend/src/models/repositories/user-group.ts b/packages/backend/src/models/repositories/user-group.ts deleted file mode 100644 index daec94490e..0000000000 --- a/packages/backend/src/models/repositories/user-group.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { UserGroup } from "@/models/entities/user-group.js"; -import { UserGroupJoinings } from "../index.js"; -import type { Packed } from "@/misc/schema.js"; - -export const UserGroupRepository = db.getRepository(UserGroup).extend({ - async pack(src: UserGroup["id"] | UserGroup): Promise<Packed<"UserGroup">> { - const userGroup = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - const users = await UserGroupJoinings.findBy({ - userGroupId: userGroup.id, - }); - - return { - id: userGroup.id, - createdAt: userGroup.createdAt.toISOString(), - name: userGroup.name, - ownerId: userGroup.userId, - userIds: users.map((x) => x.userId), - }; - }, -}); diff --git a/packages/backend/src/models/repositories/user-list.ts b/packages/backend/src/models/repositories/user-list.ts deleted file mode 100644 index e3abeac3f6..0000000000 --- a/packages/backend/src/models/repositories/user-list.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { db } from "@/db/postgre.js"; -import { UserList } from "@/models/entities/user-list.js"; -import { UserListJoinings } from "../index.js"; -import type { Packed } from "@/misc/schema.js"; - -export const UserListRepository = db.getRepository(UserList).extend({ - async pack(src: UserList["id"] | UserList): Promise<Packed<"UserList">> { - const userList = - typeof src === "object" ? src : await this.findOneByOrFail({ id: src }); - - const users = await UserListJoinings.findBy({ - userListId: userList.id, - }); - - return { - id: userList.id, - createdAt: userList.createdAt.toISOString(), - name: userList.name, - userIds: users.map((x) => x.userId), - }; - }, -}); diff --git a/packages/backend/src/models/repositories/user.ts b/packages/backend/src/models/repositories/user.ts deleted file mode 100644 index f6fcdae296..0000000000 --- a/packages/backend/src/models/repositories/user.ts +++ /dev/null @@ -1,619 +0,0 @@ -import { URL } from "url"; -import { In, Not } from "typeorm"; -import Ajv from "ajv"; -import type { ILocalUser, IRemoteUser } from "@/models/entities/user.js"; -import { User } from "@/models/entities/user.js"; -import config from "@/config/index.js"; -import type { Packed } from "@/misc/schema.js"; -import type { Promiseable } from "@/prelude/await-all.js"; -import { awaitAll } from "@/prelude/await-all.js"; -import { populateEmojis } from "@/misc/populate-emojis.js"; -import { getAntennas } from "@/misc/antenna-cache.js"; -import { USER_ACTIVE_THRESHOLD, USER_ONLINE_THRESHOLD } from "@/const.js"; -import { Cache } from "@/misc/cache.js"; -import { db } from "@/db/postgre.js"; -import { isActor, getApId } from "@/remote/activitypub/type.js"; -import DbResolver from "@/remote/activitypub/db-resolver.js"; -import Resolver from "@/remote/activitypub/resolver.js"; -import { createPerson } from "@/remote/activitypub/models/person.js"; -import { - AnnouncementReads, - Announcements, - AntennaNotes, - Blockings, - ChannelFollowings, - DriveFiles, - Followings, - FollowRequests, - Instances, - MessagingMessages, - Mutings, - RenoteMutings, - Notes, - NoteUnreads, - Notifications, - Pages, - UserGroupJoinings, - UserNotePinings, - UserProfiles, - UserSecurityKeys, -} from "../index.js"; -import type { Instance } from "../entities/instance.js"; - -const userInstanceCache = new Cache<Instance | null>(1000 * 60 * 60 * 3); - -type IsUserDetailed<Detailed extends boolean> = Detailed extends true - ? Packed<"UserDetailed"> - : Packed<"UserLite">; -type IsMeAndIsUserDetailed< - ExpectsMe extends boolean | null, - Detailed extends boolean, -> = Detailed extends true - ? ExpectsMe extends true - ? Packed<"MeDetailed"> - : ExpectsMe extends false - ? Packed<"UserDetailedNotMe"> - : Packed<"UserDetailed"> - : Packed<"UserLite">; - -const ajv = new Ajv(); - -const localUsernameSchema = { - type: "string", - pattern: /^\w{1,20}$/.toString().slice(1, -1), -} as const; -const passwordSchema = { type: "string", minLength: 1 } as const; -const nameSchema = { type: "string", minLength: 1, maxLength: 50 } as const; -const descriptionSchema = { - type: "string", - minLength: 1, - maxLength: 2048, -} as const; -const locationSchema = { type: "string", minLength: 1, maxLength: 50 } as const; -const birthdaySchema = { - type: "string", - pattern: /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/.toString().slice(1, -1), -} as const; - -function isLocalUser(user: User): user is ILocalUser; -function isLocalUser<T extends { host: User["host"] }>( - user: T, -): user is T & { host: null }; -/** - * Returns true if the user is local. - * - * @param user The user to check. - * @returns True if the user is local. - */ -function isLocalUser(user: User | { host: User["host"] }): boolean { - return user.host == null; -} - -function isRemoteUser(user: User): user is IRemoteUser; -function isRemoteUser<T extends { host: User["host"] }>( - user: T, -): user is T & { host: string }; -/** - * Returns true if the user is remote. - * - * @param user The user to check. - * @returns True if the user is remote. - */ -function isRemoteUser(user: User | { host: User["host"] }): boolean { - return !isLocalUser(user); -} - -export const UserRepository = db.getRepository(User).extend({ - localUsernameSchema, - passwordSchema, - nameSchema, - descriptionSchema, - locationSchema, - birthdaySchema, - - //#region Validators - validateLocalUsername: ajv.compile(localUsernameSchema), - validatePassword: ajv.compile(passwordSchema), - validateName: ajv.compile(nameSchema), - validateDescription: ajv.compile(descriptionSchema), - validateLocation: ajv.compile(locationSchema), - validateBirthday: ajv.compile(birthdaySchema), - //#endregion - - async getRelation(me: User["id"], target: User["id"]) { - return awaitAll({ - id: target, - isFollowing: Followings.count({ - where: { - followerId: me, - followeeId: target, - }, - take: 1, - }).then((n) => n > 0), - isFollowed: Followings.count({ - where: { - followerId: target, - followeeId: me, - }, - take: 1, - }).then((n) => n > 0), - hasPendingFollowRequestFromYou: FollowRequests.count({ - where: { - followerId: me, - followeeId: target, - }, - take: 1, - }).then((n) => n > 0), - hasPendingFollowRequestToYou: FollowRequests.count({ - where: { - followerId: target, - followeeId: me, - }, - take: 1, - }).then((n) => n > 0), - isBlocking: Blockings.count({ - where: { - blockerId: me, - blockeeId: target, - }, - take: 1, - }).then((n) => n > 0), - isBlocked: Blockings.count({ - where: { - blockerId: target, - blockeeId: me, - }, - take: 1, - }).then((n) => n > 0), - isMuted: Mutings.count({ - where: { - muterId: me, - muteeId: target, - }, - take: 1, - }).then((n) => n > 0), - isRenoteMuted: RenoteMutings.count({ - where: { - muterId: me, - muteeId: target, - }, - take: 1, - }).then((n) => n > 0), - }); - }, - - async getHasUnreadMessagingMessage(userId: User["id"]): Promise<boolean> { - const mute = await Mutings.findBy({ - muterId: userId, - }); - - const joinings = await UserGroupJoinings.findBy({ userId: userId }); - - const groupQs = Promise.all( - joinings.map((j) => - MessagingMessages.createQueryBuilder("message") - .where("message.groupId = :groupId", { groupId: j.userGroupId }) - .andWhere("message.userId != :userId", { userId: userId }) - .andWhere("NOT (:userId = ANY(message.reads))", { userId: userId }) - .andWhere("message.createdAt > :joinedAt", { joinedAt: j.createdAt }) // 自分が加入する前の会話については、未読扱いしない - .getOne() - .then((x) => x != null), - ), - ); - - const [withUser, withGroups] = await Promise.all([ - MessagingMessages.count({ - where: { - recipientId: userId, - isRead: false, - ...(mute.length > 0 - ? { userId: Not(In(mute.map((x) => x.muteeId))) } - : {}), - }, - take: 1, - }).then((count) => count > 0), - groupQs, - ]); - - return withUser || withGroups.some((x) => x); - }, - - async getHasUnreadAnnouncement(userId: User["id"]): Promise<boolean> { - const reads = await AnnouncementReads.findBy({ - userId: userId, - }); - - const count = await Announcements.countBy( - reads.length > 0 - ? { - id: Not(In(reads.map((read) => read.announcementId))), - } - : {}, - ); - - return count > 0; - }, - - async userFromURI(uri: string): Promise<User | null> { - const dbResolver = new DbResolver(); - let local = await dbResolver.getUserFromApId(uri); - if (local) { - return local; - } - - // fetching Object once from remote - const resolver = new Resolver(); - const object = (await resolver.resolve(uri)) as any; - - // /@user If a URI other than the id is specified, - // the URI is determined here - if (uri !== object.id) { - local = await dbResolver.getUserFromApId(object.id); - if (local != null) return local; - } - - return isActor(object) ? await createPerson(getApId(object)) : null; - }, - - async getHasUnreadAntenna(userId: User["id"]): Promise<boolean> { - const myAntennas = (await getAntennas()).filter((a) => a.userId === userId); - - const unread = - myAntennas.length > 0 - ? await AntennaNotes.findOneBy({ - antennaId: In(myAntennas.map((x) => x.id)), - read: false, - }) - : null; - - return unread != null; - }, - - async getHasUnreadChannel(userId: User["id"]): Promise<boolean> { - const channels = await ChannelFollowings.findBy({ followerId: userId }); - - const unread = - channels.length > 0 - ? await NoteUnreads.findOneBy({ - userId: userId, - noteChannelId: In(channels.map((x) => x.followeeId)), - }) - : null; - - return unread != null; - }, - - async getHasUnreadNotification(userId: User["id"]): Promise<boolean> { - const mute = await Mutings.findBy({ - muterId: userId, - }); - const mutedUserIds = mute.map((m) => m.muteeId); - - const count = await Notifications.count({ - where: { - notifieeId: userId, - ...(mutedUserIds.length > 0 - ? { notifierId: Not(In(mutedUserIds)) } - : {}), - isRead: false, - }, - take: 1, - }); - - return count > 0; - }, - - async getHasPendingReceivedFollowRequest( - userId: User["id"], - ): Promise<boolean> { - const count = await FollowRequests.countBy({ - followeeId: userId, - }); - - return count > 0; - }, - - getOnlineStatus(user: User): "unknown" | "online" | "active" | "offline" { - if (user.hideOnlineStatus) return "unknown"; - if (user.lastActiveDate == null) return "unknown"; - const elapsed = Date.now() - user.lastActiveDate.getTime(); - return elapsed < USER_ONLINE_THRESHOLD - ? "online" - : elapsed < USER_ACTIVE_THRESHOLD - ? "active" - : "offline"; - }, - - async getAvatarUrl(user: User): Promise<string> { - if (user.avatar) { - return ( - DriveFiles.getPublicUrl(user.avatar, true) || - this.getIdenticonUrl(user.id) - ); - } else if (user.avatarId) { - const avatar = await DriveFiles.findOneByOrFail({ id: user.avatarId }); - return ( - DriveFiles.getPublicUrl(avatar, true) || this.getIdenticonUrl(user.id) - ); - } else { - return this.getIdenticonUrl(user.id); - } - }, - - getAvatarUrlSync(user: User): string { - if (user.avatar) { - return ( - DriveFiles.getPublicUrl(user.avatar, true) || - this.getIdenticonUrl(user.id) - ); - } else { - return this.getIdenticonUrl(user.id); - } - }, - - getIdenticonUrl(userId: User["id"]): string { - return `${config.url}/identicon/${userId}`; - }, - - async pack< - ExpectsMe extends boolean | null = null, - D extends boolean = false, - >( - src: User["id"] | User, - me?: { id: User["id"] } | null | undefined, - options?: { - detail?: D; - includeSecrets?: boolean; - }, - ): Promise<IsMeAndIsUserDetailed<ExpectsMe, D>> { - const opts = Object.assign( - { - detail: false, - includeSecrets: false, - }, - options, - ); - - let user: User; - - if (typeof src === "object") { - user = src; - if (src.avatar === undefined && src.avatarId) - src.avatar = (await DriveFiles.findOneBy({ id: src.avatarId })) ?? null; - if (src.banner === undefined && src.bannerId) - src.banner = (await DriveFiles.findOneBy({ id: src.bannerId })) ?? null; - } else { - user = await this.findOneOrFail({ - where: { id: src }, - relations: { - avatar: true, - banner: true, - }, - }); - } - - const meId = me ? me.id : null; - const isMe = meId === user.id; - - const relation = - meId && !isMe && opts.detail - ? await this.getRelation(meId, user.id) - : null; - const pins = opts.detail - ? await UserNotePinings.createQueryBuilder("pin") - .where("pin.userId = :userId", { userId: user.id }) - .innerJoinAndSelect("pin.note", "note") - .orderBy("pin.id", "DESC") - .getMany() - : []; - const profile = opts.detail - ? await UserProfiles.findOneByOrFail({ userId: user.id }) - : null; - - const followingCount = - profile == null - ? null - : profile.ffVisibility === "public" || isMe - ? user.followingCount - : profile.ffVisibility === "followers" && - relation && - relation.isFollowing - ? user.followingCount - : null; - - const followersCount = - profile == null - ? null - : profile.ffVisibility === "public" || isMe - ? user.followersCount - : profile.ffVisibility === "followers" && - relation && - relation.isFollowing - ? user.followersCount - : null; - - const falsy = opts.detail ? false : undefined; - - const packed = { - id: user.id, - name: user.name, - username: user.username, - host: user.host, - avatarUrl: this.getAvatarUrlSync(user), - avatarBlurhash: user.avatar?.blurhash || null, - avatarColor: null, // 後方互換性のため - isAdmin: user.isAdmin || falsy, - isModerator: user.isModerator || falsy, - isBot: user.isBot || falsy, - isCat: user.isCat || falsy, - speakAsCat: user.speakAsCat || falsy, - instance: user.host - ? userInstanceCache - .fetch( - user.host, - () => Instances.findOneBy({ host: user.host! }), - (v) => v != null, - ) - .then((instance) => - instance - ? { - name: instance.name, - softwareName: instance.softwareName, - softwareVersion: instance.softwareVersion, - iconUrl: instance.iconUrl, - faviconUrl: instance.faviconUrl, - themeColor: instance.themeColor, - } - : undefined, - ) - : undefined, - emojis: populateEmojis(user.emojis, user.host), - onlineStatus: this.getOnlineStatus(user), - driveCapacityOverrideMb: user.driveCapacityOverrideMb, - - ...(opts.detail - ? { - url: profile!.url, - uri: user.uri, - movedToUri: user.movedToUri - ? await this.userFromURI(user.movedToUri) - : null, - alsoKnownAs: user.alsoKnownAs, - createdAt: user.createdAt.toISOString(), - updatedAt: user.updatedAt ? user.updatedAt.toISOString() : null, - lastFetchedAt: user.lastFetchedAt - ? user.lastFetchedAt.toISOString() - : null, - bannerUrl: user.banner - ? DriveFiles.getPublicUrl(user.banner, false) - : null, - bannerBlurhash: user.banner?.blurhash || null, - bannerColor: null, // 後方互換性のため - isLocked: user.isLocked, - isSilenced: user.isSilenced || falsy, - isSuspended: user.isSuspended || falsy, - description: profile!.description, - location: profile!.location, - birthday: profile!.birthday, - lang: profile!.lang, - fields: profile!.fields, - followersCount: followersCount || 0, - followingCount: followingCount || 0, - notesCount: user.notesCount, - pinnedNoteIds: pins.map((pin) => pin.noteId), - pinnedNotes: Notes.packMany( - pins.map((pin) => pin.note!), - me, - { - detail: true, - }, - ), - pinnedPageId: profile!.pinnedPageId, - pinnedPage: profile!.pinnedPageId - ? Pages.pack(profile!.pinnedPageId, me) - : null, - publicReactions: profile!.publicReactions, - ffVisibility: profile!.ffVisibility, - twoFactorEnabled: profile!.twoFactorEnabled, - usePasswordLessLogin: profile!.usePasswordLessLogin, - securityKeys: profile!.twoFactorEnabled - ? UserSecurityKeys.countBy({ - userId: user.id, - }).then((result) => result >= 1) - : false, - } - : {}), - - ...(opts.detail && isMe - ? { - avatarId: user.avatarId, - bannerId: user.bannerId, - injectFeaturedNote: profile!.injectFeaturedNote, - receiveAnnouncementEmail: profile!.receiveAnnouncementEmail, - alwaysMarkNsfw: profile!.alwaysMarkNsfw, - autoSensitive: profile!.autoSensitive, - carefulBot: profile!.carefulBot, - autoAcceptFollowed: profile!.autoAcceptFollowed, - noCrawle: profile!.noCrawle, - isExplorable: user.isExplorable, - isDeleted: user.isDeleted, - hideOnlineStatus: user.hideOnlineStatus, - hasUnreadSpecifiedNotes: NoteUnreads.count({ - where: { userId: user.id, isSpecified: true }, - take: 1, - }).then((count) => count > 0), - hasUnreadMentions: NoteUnreads.count({ - where: { userId: user.id, isMentioned: true }, - take: 1, - }).then((count) => count > 0), - hasUnreadAnnouncement: this.getHasUnreadAnnouncement(user.id), - hasUnreadAntenna: this.getHasUnreadAntenna(user.id), - hasUnreadChannel: this.getHasUnreadChannel(user.id), - hasUnreadMessagingMessage: this.getHasUnreadMessagingMessage( - user.id, - ), - hasUnreadNotification: this.getHasUnreadNotification(user.id), - hasPendingReceivedFollowRequest: - this.getHasPendingReceivedFollowRequest(user.id), - integrations: profile!.integrations, - mutedWords: profile!.mutedWords, - mutedInstances: profile!.mutedInstances, - mutingNotificationTypes: profile!.mutingNotificationTypes, - emailNotificationTypes: profile!.emailNotificationTypes, - showTimelineReplies: user.showTimelineReplies || falsy, - } - : {}), - - ...(opts.includeSecrets - ? { - email: profile!.email, - emailVerified: profile!.emailVerified, - securityKeysList: profile!.twoFactorEnabled - ? UserSecurityKeys.find({ - where: { - userId: user.id, - }, - select: { - id: true, - name: true, - lastUsed: true, - }, - }) - : [], - } - : {}), - - ...(relation - ? { - isFollowing: relation.isFollowing, - isFollowed: relation.isFollowed, - hasPendingFollowRequestFromYou: - relation.hasPendingFollowRequestFromYou, - hasPendingFollowRequestToYou: relation.hasPendingFollowRequestToYou, - isBlocking: relation.isBlocking, - isBlocked: relation.isBlocked, - isMuted: relation.isMuted, - isRenoteMuted: relation.isRenoteMuted, - } - : {}), - } as Promiseable<Packed<"User">> as Promiseable< - IsMeAndIsUserDetailed<ExpectsMe, D> - >; - - return await awaitAll(packed); - }, - - packMany<D extends boolean = false>( - users: (User["id"] | User)[], - me?: { id: User["id"] } | null | undefined, - options?: { - detail?: D; - includeSecrets?: boolean; - }, - ): Promise<IsUserDetailed<D>[]> { - return Promise.all(users.map((u) => this.pack(u, me, options))); - }, - - isLocalUser, - isRemoteUser, -}); diff --git a/packages/backend/src/models/schema/antenna.ts b/packages/backend/src/models/schema/antenna.ts deleted file mode 100644 index 990e2daa2c..0000000000 --- a/packages/backend/src/models/schema/antenna.ts +++ /dev/null @@ -1,118 +0,0 @@ -export const packedAntennaSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - name: { - type: "string", - optional: false, - nullable: false, - }, - keywords: { - type: "array", - optional: false, - nullable: false, - items: { - type: "array", - optional: false, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - }, - excludeKeywords: { - type: "array", - optional: false, - nullable: false, - items: { - type: "array", - optional: false, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - }, - src: { - type: "string", - optional: false, - nullable: false, - enum: ["home", "all", "users", "list", "group", "instances"], - }, - userListId: { - type: "string", - optional: false, - nullable: true, - format: "id", - }, - userGroupId: { - type: "string", - optional: false, - nullable: true, - format: "id", - }, - users: { - type: "array", - optional: false, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - instances: { - type: "array", - optional: false, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - caseSensitive: { - type: "boolean", - optional: false, - nullable: false, - default: false, - }, - notify: { - type: "boolean", - optional: false, - nullable: false, - }, - withReplies: { - type: "boolean", - optional: false, - nullable: false, - default: false, - }, - withFile: { - type: "boolean", - optional: false, - nullable: false, - }, - hasUnreadNote: { - type: "boolean", - optional: false, - nullable: false, - default: false, - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/app.ts b/packages/backend/src/models/schema/app.ts deleted file mode 100644 index 8ec71159a3..0000000000 --- a/packages/backend/src/models/schema/app.ts +++ /dev/null @@ -1,40 +0,0 @@ -export const packedAppSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - }, - name: { - type: "string", - optional: false, - nullable: false, - }, - callbackUrl: { - type: "string", - optional: false, - nullable: true, - }, - permission: { - type: "array", - optional: false, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - secret: { - type: "string", - optional: true, - nullable: false, - }, - isAuthorized: { - type: "boolean", - optional: true, - nullable: false, - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/blocking.ts b/packages/backend/src/models/schema/blocking.ts deleted file mode 100644 index 1d491e9395..0000000000 --- a/packages/backend/src/models/schema/blocking.ts +++ /dev/null @@ -1,30 +0,0 @@ -export const packedBlockingSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - blockeeId: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - blockee: { - type: "object", - optional: false, - nullable: false, - ref: "UserDetailed", - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/channel.ts b/packages/backend/src/models/schema/channel.ts deleted file mode 100644 index 67833cb0dd..0000000000 --- a/packages/backend/src/models/schema/channel.ts +++ /dev/null @@ -1,61 +0,0 @@ -export const packedChannelSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - lastNotedAt: { - type: "string", - optional: false, - nullable: true, - format: "date-time", - }, - name: { - type: "string", - optional: false, - nullable: false, - }, - description: { - type: "string", - nullable: true, - optional: false, - }, - bannerUrl: { - type: "string", - format: "url", - nullable: true, - optional: false, - }, - notesCount: { - type: "number", - nullable: false, - optional: false, - }, - usersCount: { - type: "number", - nullable: false, - optional: false, - }, - isFollowing: { - type: "boolean", - optional: true, - nullable: false, - }, - userId: { - type: "string", - nullable: true, - optional: false, - format: "id", - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/clip.ts b/packages/backend/src/models/schema/clip.ts deleted file mode 100644 index 651303ad9f..0000000000 --- a/packages/backend/src/models/schema/clip.ts +++ /dev/null @@ -1,45 +0,0 @@ -export const packedClipSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - userId: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - user: { - type: "object", - ref: "UserLite", - optional: false, - nullable: false, - }, - name: { - type: "string", - optional: false, - nullable: false, - }, - description: { - type: "string", - optional: false, - nullable: true, - }, - isPublic: { - type: "boolean", - optional: false, - nullable: false, - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/drive-file.ts b/packages/backend/src/models/schema/drive-file.ts deleted file mode 100644 index 30db9e7d48..0000000000 --- a/packages/backend/src/models/schema/drive-file.ts +++ /dev/null @@ -1,127 +0,0 @@ -export const packedDriveFileSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - name: { - type: "string", - optional: false, - nullable: false, - example: "lenna.jpg", - }, - type: { - type: "string", - optional: false, - nullable: false, - example: "image/jpeg", - }, - md5: { - type: "string", - optional: false, - nullable: false, - format: "md5", - example: "15eca7fba0480996e2245f5185bf39f2", - }, - size: { - type: "number", - optional: false, - nullable: false, - example: 51469, - }, - isSensitive: { - type: "boolean", - optional: false, - nullable: false, - }, - blurhash: { - type: "string", - optional: false, - nullable: true, - }, - properties: { - type: "object", - optional: false, - nullable: false, - properties: { - width: { - type: "number", - optional: true, - nullable: false, - example: 1280, - }, - height: { - type: "number", - optional: true, - nullable: false, - example: 720, - }, - orientation: { - type: "number", - optional: true, - nullable: false, - example: 8, - }, - avgColor: { - type: "string", - optional: true, - nullable: false, - example: "rgb(40,65,87)", - }, - }, - }, - url: { - type: "string", - optional: false, - nullable: true, - format: "url", - }, - thumbnailUrl: { - type: "string", - optional: false, - nullable: true, - format: "url", - }, - comment: { - type: "string", - optional: false, - nullable: true, - }, - folderId: { - type: "string", - optional: false, - nullable: true, - format: "id", - example: "xxxxxxxxxx", - }, - folder: { - type: "object", - optional: true, - nullable: true, - ref: "DriveFolder", - }, - userId: { - type: "string", - optional: false, - nullable: true, - format: "id", - example: "xxxxxxxxxx", - }, - user: { - type: "object", - optional: true, - nullable: true, - ref: "UserLite", - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/drive-folder.ts b/packages/backend/src/models/schema/drive-folder.ts deleted file mode 100644 index 2298b5420c..0000000000 --- a/packages/backend/src/models/schema/drive-folder.ts +++ /dev/null @@ -1,46 +0,0 @@ -export const packedDriveFolderSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - name: { - type: "string", - optional: false, - nullable: false, - }, - foldersCount: { - type: "number", - optional: true, - nullable: false, - }, - filesCount: { - type: "number", - optional: true, - nullable: false, - }, - parentId: { - type: "string", - optional: false, - nullable: true, - format: "id", - example: "xxxxxxxxxx", - }, - parent: { - type: "object", - optional: true, - nullable: true, - ref: "DriveFolder", - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/emoji.ts b/packages/backend/src/models/schema/emoji.ts deleted file mode 100644 index 8994381b31..0000000000 --- a/packages/backend/src/models/schema/emoji.ts +++ /dev/null @@ -1,49 +0,0 @@ -export const packedEmojiSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - aliases: { - type: "array", - optional: false, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - }, - name: { - type: "string", - optional: false, - nullable: false, - }, - category: { - type: "string", - optional: false, - nullable: true, - }, - host: { - type: "string", - optional: false, - nullable: true, - description: "The local host is represented with `null`.", - }, - url: { - type: "string", - optional: false, - nullable: false, - }, - license: { - type: "string", - optional: false, - nullable: true, - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/federation-instance.ts b/packages/backend/src/models/schema/federation-instance.ts deleted file mode 100644 index ed3369bf11..0000000000 --- a/packages/backend/src/models/schema/federation-instance.ts +++ /dev/null @@ -1,133 +0,0 @@ -import config from "@/config/index.js"; - -export const packedFederationInstanceSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - caughtAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - host: { - type: "string", - optional: false, - nullable: false, - example: "calckey.example.com", - }, - usersCount: { - type: "number", - optional: false, - nullable: false, - }, - notesCount: { - type: "number", - optional: false, - nullable: false, - }, - followingCount: { - type: "number", - optional: false, - nullable: false, - }, - followersCount: { - type: "number", - optional: false, - nullable: false, - }, - latestRequestSentAt: { - type: "string", - optional: false, - nullable: true, - format: "date-time", - }, - lastCommunicatedAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - isNotResponding: { - type: "boolean", - optional: false, - nullable: false, - }, - isSuspended: { - type: "boolean", - optional: false, - nullable: false, - }, - isBlocked: { - type: "boolean", - optional: false, - nullable: false, - }, - softwareName: { - type: "string", - optional: false, - nullable: true, - example: "calckey", - }, - softwareVersion: { - type: "string", - optional: false, - nullable: true, - example: config.version, - }, - openRegistrations: { - type: "boolean", - optional: false, - nullable: true, - example: true, - }, - name: { - type: "string", - optional: false, - nullable: true, - }, - description: { - type: "string", - optional: false, - nullable: true, - }, - maintainerName: { - type: "string", - optional: false, - nullable: true, - }, - maintainerEmail: { - type: "string", - optional: false, - nullable: true, - }, - iconUrl: { - type: "string", - optional: false, - nullable: true, - format: "url", - }, - faviconUrl: { - type: "string", - optional: false, - nullable: true, - format: "url", - }, - themeColor: { - type: "string", - optional: false, - nullable: true, - }, - infoUpdatedAt: { - type: "string", - optional: false, - nullable: true, - format: "date-time", - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/following.ts b/packages/backend/src/models/schema/following.ts deleted file mode 100644 index f53cafaba5..0000000000 --- a/packages/backend/src/models/schema/following.ts +++ /dev/null @@ -1,42 +0,0 @@ -export const packedFollowingSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - followeeId: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - followee: { - type: "object", - optional: true, - nullable: false, - ref: "UserDetailed", - }, - followerId: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - follower: { - type: "object", - optional: true, - nullable: false, - ref: "UserDetailed", - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/gallery-post.ts b/packages/backend/src/models/schema/gallery-post.ts deleted file mode 100644 index 9ac348e1fb..0000000000 --- a/packages/backend/src/models/schema/gallery-post.ts +++ /dev/null @@ -1,83 +0,0 @@ -export const packedGalleryPostSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - updatedAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - title: { - type: "string", - optional: false, - nullable: false, - }, - description: { - type: "string", - optional: false, - nullable: true, - }, - userId: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - user: { - type: "object", - ref: "UserLite", - optional: false, - nullable: false, - }, - fileIds: { - type: "array", - optional: true, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - }, - files: { - type: "array", - optional: true, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "DriveFile", - }, - }, - tags: { - type: "array", - optional: true, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - isSensitive: { - type: "boolean", - optional: false, - nullable: false, - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/hashtag.ts b/packages/backend/src/models/schema/hashtag.ts deleted file mode 100644 index dacc515070..0000000000 --- a/packages/backend/src/models/schema/hashtag.ts +++ /dev/null @@ -1,41 +0,0 @@ -export const packedHashtagSchema = { - type: "object", - properties: { - tag: { - type: "string", - optional: false, - nullable: false, - example: "calckey", - }, - mentionedUsersCount: { - type: "number", - optional: false, - nullable: false, - }, - mentionedLocalUsersCount: { - type: "number", - optional: false, - nullable: false, - }, - mentionedRemoteUsersCount: { - type: "number", - optional: false, - nullable: false, - }, - attachedUsersCount: { - type: "number", - optional: false, - nullable: false, - }, - attachedLocalUsersCount: { - type: "number", - optional: false, - nullable: false, - }, - attachedRemoteUsersCount: { - type: "number", - optional: false, - nullable: false, - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/messaging-message.ts b/packages/backend/src/models/schema/messaging-message.ts deleted file mode 100644 index d598e6dbc6..0000000000 --- a/packages/backend/src/models/schema/messaging-message.ts +++ /dev/null @@ -1,87 +0,0 @@ -export const packedMessagingMessageSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - userId: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - user: { - type: "object", - ref: "UserLite", - optional: true, - nullable: false, - }, - text: { - type: "string", - optional: false, - nullable: true, - }, - fileId: { - type: "string", - optional: true, - nullable: true, - format: "id", - }, - file: { - type: "object", - optional: true, - nullable: true, - ref: "DriveFile", - }, - recipientId: { - type: "string", - optional: false, - nullable: true, - format: "id", - }, - recipient: { - type: "object", - optional: true, - nullable: true, - ref: "UserLite", - }, - groupId: { - type: "string", - optional: false, - nullable: true, - format: "id", - }, - group: { - type: "object", - optional: true, - nullable: true, - ref: "UserGroup", - }, - isRead: { - type: "boolean", - optional: true, - nullable: false, - }, - reads: { - type: "array", - optional: true, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/muting.ts b/packages/backend/src/models/schema/muting.ts deleted file mode 100644 index d5815f86d1..0000000000 --- a/packages/backend/src/models/schema/muting.ts +++ /dev/null @@ -1,36 +0,0 @@ -export const packedMutingSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - expiresAt: { - type: "string", - optional: false, - nullable: true, - format: "date-time", - }, - muteeId: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - mutee: { - type: "object", - optional: false, - nullable: false, - ref: "UserDetailed", - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/note-favorite.ts b/packages/backend/src/models/schema/note-favorite.ts deleted file mode 100644 index 17a42baf0e..0000000000 --- a/packages/backend/src/models/schema/note-favorite.ts +++ /dev/null @@ -1,30 +0,0 @@ -export const packedNoteFavoriteSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - note: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - noteId: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/note-reaction.ts b/packages/backend/src/models/schema/note-reaction.ts deleted file mode 100644 index 1080bdcf51..0000000000 --- a/packages/backend/src/models/schema/note-reaction.ts +++ /dev/null @@ -1,29 +0,0 @@ -export const packedNoteReactionSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - user: { - type: "object", - optional: false, - nullable: false, - ref: "UserLite", - }, - type: { - type: "string", - optional: false, - nullable: false, - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/note.ts b/packages/backend/src/models/schema/note.ts deleted file mode 100644 index e17f054e8e..0000000000 --- a/packages/backend/src/models/schema/note.ts +++ /dev/null @@ -1,200 +0,0 @@ -export const packedNoteSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - text: { - type: "string", - optional: false, - nullable: true, - }, - cw: { - type: "string", - optional: true, - nullable: true, - }, - userId: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - user: { - type: "object", - ref: "UserLite", - optional: false, - nullable: false, - }, - replyId: { - type: "string", - optional: true, - nullable: true, - format: "id", - example: "xxxxxxxxxx", - }, - renoteId: { - type: "string", - optional: true, - nullable: true, - format: "id", - example: "xxxxxxxxxx", - }, - reply: { - type: "object", - optional: true, - nullable: true, - ref: "Note", - }, - renote: { - type: "object", - optional: true, - nullable: true, - ref: "Note", - }, - visibility: { - type: "string", - optional: false, - nullable: false, - }, - mentions: { - type: "array", - optional: true, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - }, - visibleUserIds: { - type: "array", - optional: true, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - }, - fileIds: { - type: "array", - optional: true, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - }, - files: { - type: "array", - optional: true, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "DriveFile", - }, - }, - tags: { - type: "array", - optional: true, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - poll: { - type: "object", - optional: true, - nullable: true, - }, - channelId: { - type: "string", - optional: true, - nullable: true, - format: "id", - example: "xxxxxxxxxx", - }, - channel: { - type: "object", - optional: true, - nullable: true, - items: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - }, - name: { - type: "string", - optional: false, - nullable: true, - }, - }, - }, - }, - localOnly: { - type: "boolean", - optional: true, - nullable: false, - }, - emojis: { - type: "object", - optional: true, - nullable: true, - }, - reactions: { - type: "object", - optional: false, - nullable: false, - }, - renoteCount: { - type: "number", - optional: false, - nullable: false, - }, - repliesCount: { - type: "number", - optional: false, - nullable: false, - }, - uri: { - type: "string", - optional: true, - nullable: false, - }, - url: { - type: "string", - optional: true, - nullable: false, - }, - - myReaction: { - type: "object", - optional: true, - nullable: true, - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/notification.ts b/packages/backend/src/models/schema/notification.ts deleted file mode 100644 index 97fd16339c..0000000000 --- a/packages/backend/src/models/schema/notification.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { notificationTypes } from "@/types.js"; - -export const packedNotificationSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - isRead: { - type: "boolean", - optional: false, - nullable: false, - }, - type: { - type: "string", - optional: false, - nullable: false, - enum: [...notificationTypes], - }, - user: { - type: "object", - ref: "UserLite", - optional: true, - nullable: true, - }, - userId: { - type: "string", - optional: true, - nullable: true, - format: "id", - }, - note: { - type: "object", - ref: "Note", - optional: true, - nullable: true, - }, - reaction: { - type: "string", - optional: true, - nullable: true, - }, - choice: { - type: "number", - optional: true, - nullable: true, - }, - invitation: { - type: "object", - optional: true, - nullable: true, - }, - body: { - type: "string", - optional: true, - nullable: true, - }, - header: { - type: "string", - optional: true, - nullable: true, - }, - icon: { - type: "string", - optional: true, - nullable: true, - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/page.ts b/packages/backend/src/models/schema/page.ts deleted file mode 100644 index a1b9144b59..0000000000 --- a/packages/backend/src/models/schema/page.ts +++ /dev/null @@ -1,66 +0,0 @@ -export const packedPageSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - updatedAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - title: { - type: "string", - optional: false, - nullable: false, - }, - name: { - type: "string", - optional: false, - nullable: false, - }, - summary: { - type: "string", - optional: false, - nullable: true, - }, - content: { - type: "array", - optional: false, - nullable: false, - }, - variables: { - type: "array", - optional: false, - nullable: false, - }, - userId: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - user: { - type: "object", - ref: "UserLite", - optional: false, - nullable: false, - }, - isPublic: { - type: "boolean", - optional: false, - nullable: false, - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/queue.ts b/packages/backend/src/models/schema/queue.ts deleted file mode 100644 index 954ac688be..0000000000 --- a/packages/backend/src/models/schema/queue.ts +++ /dev/null @@ -1,30 +0,0 @@ -export const packedQueueCountSchema = { - type: "object", - properties: { - waiting: { - type: "number", - optional: false, - nullable: false, - }, - active: { - type: "number", - optional: false, - nullable: false, - }, - completed: { - type: "number", - optional: false, - nullable: false, - }, - failed: { - type: "number", - optional: false, - nullable: false, - }, - delayed: { - type: "number", - optional: false, - nullable: false, - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/renote-muting.ts b/packages/backend/src/models/schema/renote-muting.ts deleted file mode 100644 index 2a5824e32b..0000000000 --- a/packages/backend/src/models/schema/renote-muting.ts +++ /dev/null @@ -1,30 +0,0 @@ -export const packedRenoteMutingSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - muteeId: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - mutee: { - type: "object", - optional: false, - nullable: false, - ref: "UserDetailed", - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/user-group.ts b/packages/backend/src/models/schema/user-group.ts deleted file mode 100644 index a4a85f9699..0000000000 --- a/packages/backend/src/models/schema/user-group.ts +++ /dev/null @@ -1,40 +0,0 @@ -export const packedUserGroupSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - name: { - type: "string", - optional: false, - nullable: false, - }, - ownerId: { - type: "string", - nullable: false, - optional: false, - format: "id", - }, - userIds: { - type: "array", - nullable: false, - optional: true, - items: { - type: "string", - nullable: false, - optional: false, - format: "id", - }, - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/user-list.ts b/packages/backend/src/models/schema/user-list.ts deleted file mode 100644 index 1e203b63ae..0000000000 --- a/packages/backend/src/models/schema/user-list.ts +++ /dev/null @@ -1,34 +0,0 @@ -export const packedUserListSchema = { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - name: { - type: "string", - optional: false, - nullable: false, - }, - userIds: { - type: "array", - nullable: false, - optional: true, - items: { - type: "string", - nullable: false, - optional: false, - format: "id", - }, - }, - }, -} as const; diff --git a/packages/backend/src/models/schema/user.ts b/packages/backend/src/models/schema/user.ts deleted file mode 100644 index 80e94fe508..0000000000 --- a/packages/backend/src/models/schema/user.ts +++ /dev/null @@ -1,583 +0,0 @@ -export const packedUserLiteSchema = { - type: "object", - properties: { - id: { - type: "string", - nullable: false, - optional: false, - format: "id", - example: "xxxxxxxxxx", - }, - name: { - type: "string", - nullable: true, - optional: false, - example: "藍", - }, - username: { - type: "string", - nullable: false, - optional: false, - example: "calc", - }, - host: { - type: "string", - nullable: true, - optional: false, - example: "misskey.example.com", - description: "The local host is represented with `null`.", - }, - avatarUrl: { - type: "string", - format: "url", - nullable: true, - optional: false, - }, - avatarBlurhash: { - type: "any", - nullable: true, - optional: false, - }, - avatarColor: { - type: "any", - nullable: true, - optional: false, - default: null, - }, - isAdmin: { - type: "boolean", - nullable: false, - optional: true, - default: false, - }, - isModerator: { - type: "boolean", - nullable: false, - optional: true, - default: false, - }, - isBot: { - type: "boolean", - nullable: false, - optional: true, - }, - isCat: { - type: "boolean", - nullable: false, - optional: true, - }, - speakAsCat: { - type: "boolean", - nullable: false, - optional: true, - }, - emojis: { - type: "array", - nullable: false, - optional: false, - items: { - type: "object", - nullable: false, - optional: false, - properties: { - name: { - type: "string", - nullable: false, - optional: false, - }, - url: { - type: "string", - nullable: false, - optional: false, - format: "url", - }, - }, - }, - }, - onlineStatus: { - type: "string", - format: "url", - nullable: true, - optional: false, - enum: ["unknown", "online", "active", "offline"], - }, - }, -} as const; - -export const packedUserDetailedNotMeOnlySchema = { - type: "object", - properties: { - url: { - type: "string", - format: "url", - nullable: true, - optional: false, - }, - uri: { - type: "string", - format: "uri", - nullable: true, - optional: false, - }, - movedToUri: { - type: "string", - format: "uri", - nullable: true, - optional: false, - }, - alsoKnownAs: { - type: "array", - format: "uri", - nullable: true, - optional: false, - }, - createdAt: { - type: "string", - nullable: false, - optional: false, - format: "date-time", - }, - updatedAt: { - type: "string", - nullable: true, - optional: false, - format: "date-time", - }, - lastFetchedAt: { - type: "string", - nullable: true, - optional: false, - format: "date-time", - }, - bannerUrl: { - type: "string", - format: "url", - nullable: true, - optional: false, - }, - bannerBlurhash: { - type: "any", - nullable: true, - optional: false, - }, - bannerColor: { - type: "any", - nullable: true, - optional: false, - default: null, - }, - isLocked: { - type: "boolean", - nullable: false, - optional: false, - }, - isSilenced: { - type: "boolean", - nullable: false, - optional: false, - }, - isSuspended: { - type: "boolean", - nullable: false, - optional: false, - example: false, - }, - description: { - type: "string", - nullable: true, - optional: false, - example: "Hi masters, I am Ai!", - }, - location: { - type: "string", - nullable: true, - optional: false, - }, - birthday: { - type: "string", - nullable: true, - optional: false, - example: "2018-03-12", - }, - lang: { - type: "string", - nullable: true, - optional: false, - example: "ja-JP", - }, - fields: { - type: "array", - nullable: false, - optional: false, - items: { - type: "object", - nullable: false, - optional: false, - properties: { - name: { - type: "string", - nullable: false, - optional: false, - }, - value: { - type: "string", - nullable: false, - optional: false, - }, - }, - maxLength: 4, - }, - }, - followersCount: { - type: "number", - nullable: false, - optional: false, - }, - followingCount: { - type: "number", - nullable: false, - optional: false, - }, - notesCount: { - type: "number", - nullable: false, - optional: false, - }, - pinnedNoteIds: { - type: "array", - nullable: false, - optional: false, - items: { - type: "string", - nullable: false, - optional: false, - format: "id", - }, - }, - pinnedNotes: { - type: "array", - nullable: false, - optional: false, - items: { - type: "object", - nullable: false, - optional: false, - ref: "Note", - }, - }, - pinnedPageId: { - type: "string", - nullable: true, - optional: false, - }, - pinnedPage: { - type: "object", - nullable: true, - optional: false, - ref: "Page", - }, - publicReactions: { - type: "boolean", - nullable: false, - optional: false, - }, - twoFactorEnabled: { - type: "boolean", - nullable: false, - optional: false, - default: false, - }, - usePasswordLessLogin: { - type: "boolean", - nullable: false, - optional: false, - default: false, - }, - securityKeys: { - type: "boolean", - nullable: false, - optional: false, - default: false, - }, - //#region relations - isFollowing: { - type: "boolean", - nullable: false, - optional: true, - }, - isFollowed: { - type: "boolean", - nullable: false, - optional: true, - }, - hasPendingFollowRequestFromYou: { - type: "boolean", - nullable: false, - optional: true, - }, - hasPendingFollowRequestToYou: { - type: "boolean", - nullable: false, - optional: true, - }, - isBlocking: { - type: "boolean", - nullable: false, - optional: true, - }, - isBlocked: { - type: "boolean", - nullable: false, - optional: true, - }, - isMuted: { - type: "boolean", - nullable: false, - optional: true, - }, - isRenoteMuted: { - type: "boolean", - nullable: false, - optional: true, - }, - //#endregion - }, -} as const; - -export const packedMeDetailedOnlySchema = { - type: "object", - properties: { - avatarId: { - type: "string", - nullable: true, - optional: false, - format: "id", - }, - bannerId: { - type: "string", - nullable: true, - optional: false, - format: "id", - }, - injectFeaturedNote: { - type: "boolean", - nullable: true, - optional: false, - }, - receiveAnnouncementEmail: { - type: "boolean", - nullable: true, - optional: false, - }, - alwaysMarkNsfw: { - type: "boolean", - nullable: true, - optional: false, - }, - autoSensitive: { - type: "boolean", - nullable: true, - optional: false, - }, - carefulBot: { - type: "boolean", - nullable: true, - optional: false, - }, - autoAcceptFollowed: { - type: "boolean", - nullable: true, - optional: false, - }, - noCrawle: { - type: "boolean", - nullable: true, - optional: false, - }, - isExplorable: { - type: "boolean", - nullable: false, - optional: false, - }, - isDeleted: { - type: "boolean", - nullable: false, - optional: false, - }, - hideOnlineStatus: { - type: "boolean", - nullable: false, - optional: false, - }, - hasUnreadSpecifiedNotes: { - type: "boolean", - nullable: false, - optional: false, - }, - hasUnreadMentions: { - type: "boolean", - nullable: false, - optional: false, - }, - hasUnreadAnnouncement: { - type: "boolean", - nullable: false, - optional: false, - }, - hasUnreadAntenna: { - type: "boolean", - nullable: false, - optional: false, - }, - hasUnreadChannel: { - type: "boolean", - nullable: false, - optional: false, - }, - hasUnreadMessagingMessage: { - type: "boolean", - nullable: false, - optional: false, - }, - hasUnreadNotification: { - type: "boolean", - nullable: false, - optional: false, - }, - hasPendingReceivedFollowRequest: { - type: "boolean", - nullable: false, - optional: false, - }, - integrations: { - type: "object", - nullable: true, - optional: false, - }, - mutedWords: { - type: "array", - nullable: false, - optional: false, - items: { - type: "array", - nullable: false, - optional: false, - items: { - type: "string", - nullable: false, - optional: false, - }, - }, - }, - mutedInstances: { - type: "array", - nullable: true, - optional: false, - items: { - type: "string", - nullable: false, - optional: false, - }, - }, - mutingNotificationTypes: { - type: "array", - nullable: true, - optional: false, - items: { - type: "string", - nullable: false, - optional: false, - }, - }, - emailNotificationTypes: { - type: "array", - nullable: true, - optional: false, - items: { - type: "string", - nullable: false, - optional: false, - }, - }, - //#region secrets - email: { - type: "string", - nullable: true, - optional: true, - }, - emailVerified: { - type: "boolean", - nullable: true, - optional: true, - }, - securityKeysList: { - type: "array", - nullable: false, - optional: true, - items: { - type: "object", - nullable: false, - optional: false, - }, - }, - //#endregion - }, -} as const; - -export const packedUserDetailedNotMeSchema = { - type: "object", - allOf: [ - { - type: "object", - ref: "UserLite", - }, - { - type: "object", - ref: "UserDetailedNotMeOnly", - }, - ], -} as const; - -export const packedMeDetailedSchema = { - type: "object", - allOf: [ - { - type: "object", - ref: "UserLite", - }, - { - type: "object", - ref: "UserDetailedNotMeOnly", - }, - { - type: "object", - ref: "MeDetailedOnly", - }, - ], -} as const; - -export const packedUserDetailedSchema = { - oneOf: [ - { - type: "object", - ref: "UserDetailedNotMe", - }, - { - type: "object", - ref: "MeDetailed", - }, - ], -} as const; - -export const packedUserSchema = { - oneOf: [ - { - type: "object", - ref: "UserLite", - }, - { - type: "object", - ref: "UserDetailed", - }, - ], -} as const; diff --git a/packages/backend/src/prelude/README.md b/packages/backend/src/prelude/README.md deleted file mode 100644 index bb728cfb1b..0000000000 --- a/packages/backend/src/prelude/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Prelude -このディレクトリのコードはJavaScriptの表現能力を補うためのコードです。 -Misskey固有の処理とは独立したコードの集まりですが、Misskeyのコードを読みやすくすることを目的としています。 diff --git a/packages/backend/src/prelude/array.ts b/packages/backend/src/prelude/array.ts deleted file mode 100644 index 71a24c89b7..0000000000 --- a/packages/backend/src/prelude/array.ts +++ /dev/null @@ -1,138 +0,0 @@ -import type { EndoRelation, Predicate } from "./relation.js"; - -/** - * Count the number of elements that satisfy the predicate - */ - -export function countIf<T>(f: Predicate<T>, xs: T[]): number { - return xs.filter(f).length; -} - -/** - * Count the number of elements that is equal to the element - */ -export function count<T>(a: T, xs: T[]): number { - return countIf((x) => x === a, xs); -} - -/** - * Concatenate an array of arrays - */ -export function concat<T>(xss: T[][]): T[] { - return ([] as T[]).concat(...xss); -} - -/** - * Intersperse the element between the elements of the array - * @param sep The element to be interspersed - */ -export function intersperse<T>(sep: T, xs: T[]): T[] { - return concat(xs.map((x) => [sep, x])).slice(1); -} - -/** - * Returns the array of elements that is not equal to the element - */ -export function erase<T>(a: T, xs: T[]): T[] { - return xs.filter((x) => x !== a); -} - -/** - * Finds the array of all elements in the first array not contained in the second array. - * The order of result values are determined by the first array. - */ -export function difference<T>(xs: T[], ys: T[]): T[] { - return xs.filter((x) => !ys.includes(x)); -} - -/** - * Remove all but the first element from every group of equivalent elements - */ -export function unique<T>(xs: T[]): T[] { - return [...new Set(xs)]; -} - -export function sum(xs: number[]): number { - return xs.reduce((a, b) => a + b, 0); -} - -export function maximum(xs: number[]): number { - return Math.max(...xs); -} - -/** - * Splits an array based on the equivalence relation. - * The concatenation of the result is equal to the argument. - */ -export function groupBy<T>(f: EndoRelation<T>, xs: T[]): T[][] { - const groups = [] as T[][]; - for (const x of xs) { - if (groups.length !== 0 && f(groups[groups.length - 1][0], x)) { - groups[groups.length - 1].push(x); - } else { - groups.push([x]); - } - } - return groups; -} - -/** - * Splits an array based on the equivalence relation induced by the function. - * The concatenation of the result is equal to the argument. - */ -export function groupOn<T, S>(f: (x: T) => S, xs: T[]): T[][] { - return groupBy((a, b) => f(a) === f(b), xs); -} - -export function groupByX<T>(collections: T[], keySelector: (x: T) => string) { - return collections.reduce((obj: Record<string, T[]>, item: T) => { - const key = keySelector(item); - if (!Object.prototype.hasOwnProperty.call(obj, key)) { - obj[key] = []; - } - - obj[key].push(item); - - return obj; - }, {}); -} - -/** - * Compare two arrays by lexicographical order - */ -export function lessThan(xs: number[], ys: number[]): boolean { - for (let i = 0; i < Math.min(xs.length, ys.length); i++) { - if (xs[i] < ys[i]) return true; - if (xs[i] > ys[i]) return false; - } - return xs.length < ys.length; -} - -/** - * Returns the longest prefix of elements that satisfy the predicate - */ -export function takeWhile<T>(f: Predicate<T>, xs: T[]): T[] { - const ys = []; - for (const x of xs) { - if (f(x)) { - ys.push(x); - } else { - break; - } - } - return ys; -} - -export function cumulativeSum(xs: number[]): number[] { - const ys = Array.from(xs); // deep copy - for (let i = 1; i < ys.length; i++) ys[i] += ys[i - 1]; - return ys; -} - -export function toArray<T>(x: T | T[] | undefined): T[] { - return Array.isArray(x) ? x : x != null ? [x] : []; -} - -export function toSingle<T>(x: T | T[] | undefined): T | undefined { - return Array.isArray(x) ? x[0] : x; -} diff --git a/packages/backend/src/prelude/await-all.ts b/packages/backend/src/prelude/await-all.ts deleted file mode 100644 index ce11eb87b4..0000000000 --- a/packages/backend/src/prelude/await-all.ts +++ /dev/null @@ -1,23 +0,0 @@ -export type Promiseable<T> = { - [K in keyof T]: Promise<T[K]> | T[K]; -}; - -export async function awaitAll<T>(obj: Promiseable<T>): Promise<T> { - const target = {} as T; - const keys = Object.keys(obj) as unknown as (keyof T)[]; - const values = Object.values(obj) as any[]; - - const resolvedValues = await Promise.all( - values.map((value) => - !value?.constructor || value.constructor.name !== "Object" - ? value - : awaitAll(value), - ), - ); - - for (let i = 0; i < keys.length; i++) { - target[keys[i]] = resolvedValues[i]; - } - - return target; -} diff --git a/packages/backend/src/prelude/math.ts b/packages/backend/src/prelude/math.ts deleted file mode 100644 index 07b94bec30..0000000000 --- a/packages/backend/src/prelude/math.ts +++ /dev/null @@ -1,3 +0,0 @@ -export function gcd(a: number, b: number): number { - return b === 0 ? a : gcd(b, a % b); -} diff --git a/packages/backend/src/prelude/maybe.ts b/packages/backend/src/prelude/maybe.ts deleted file mode 100644 index df7c4ed52a..0000000000 --- a/packages/backend/src/prelude/maybe.ts +++ /dev/null @@ -1,20 +0,0 @@ -export interface IMaybe<T> { - isJust(): this is IJust<T>; -} - -export interface IJust<T> extends IMaybe<T> { - get(): T; -} - -export function just<T>(value: T): IJust<T> { - return { - isJust: () => true, - get: () => value, - }; -} - -export function nothing<T>(): IMaybe<T> { - return { - isJust: () => false, - }; -} diff --git a/packages/backend/src/prelude/relation.ts b/packages/backend/src/prelude/relation.ts deleted file mode 100644 index 1f4703f52f..0000000000 --- a/packages/backend/src/prelude/relation.ts +++ /dev/null @@ -1,5 +0,0 @@ -export type Predicate<T> = (a: T) => boolean; - -export type Relation<T, U> = (a: T, b: U) => boolean; - -export type EndoRelation<T> = Relation<T, T>; diff --git a/packages/backend/src/prelude/string.ts b/packages/backend/src/prelude/string.ts deleted file mode 100644 index 9588825cb7..0000000000 --- a/packages/backend/src/prelude/string.ts +++ /dev/null @@ -1,15 +0,0 @@ -export function concat(xs: string[]): string { - return xs.join(""); -} - -export function capitalize(s: string): string { - return toUpperCase(s.charAt(0)) + toLowerCase(s.slice(1)); -} - -export function toUpperCase(s: string): string { - return s.toUpperCase(); -} - -export function toLowerCase(s: string): string { - return s.toLowerCase(); -} diff --git a/packages/backend/src/prelude/symbol.ts b/packages/backend/src/prelude/symbol.ts deleted file mode 100644 index 5b88467d46..0000000000 --- a/packages/backend/src/prelude/symbol.ts +++ /dev/null @@ -1 +0,0 @@ -export const fallback = Symbol("fallback"); diff --git a/packages/backend/src/prelude/time.ts b/packages/backend/src/prelude/time.ts deleted file mode 100644 index 5901b9c484..0000000000 --- a/packages/backend/src/prelude/time.ts +++ /dev/null @@ -1,54 +0,0 @@ -const dateTimeIntervals = { - day: 86400000, - hour: 3600000, - ms: 1, -}; - -export function dateUTC(time: number[]): Date { - const d = - time.length === 2 - ? Date.UTC(time[0], time[1]) - : time.length === 3 - ? Date.UTC(time[0], time[1], time[2]) - : time.length === 4 - ? Date.UTC(time[0], time[1], time[2], time[3]) - : time.length === 5 - ? Date.UTC(time[0], time[1], time[2], time[3], time[4]) - : time.length === 6 - ? Date.UTC(time[0], time[1], time[2], time[3], time[4], time[5]) - : time.length === 7 - ? Date.UTC(time[0], time[1], time[2], time[3], time[4], time[5], time[6]) - : null; - - if (!d) throw new Error("wrong number of arguments"); - - return new Date(d); -} - -export function isTimeSame(a: Date, b: Date): boolean { - return a.getTime() === b.getTime(); -} - -export function isTimeBefore(a: Date, b: Date): boolean { - return a.getTime() - b.getTime() < 0; -} - -export function isTimeAfter(a: Date, b: Date): boolean { - return a.getTime() - b.getTime() > 0; -} - -export function addTime( - x: Date, - value: number, - span: keyof typeof dateTimeIntervals = "ms", -): Date { - return new Date(x.getTime() + value * dateTimeIntervals[span]); -} - -export function subtractTime( - x: Date, - value: number, - span: keyof typeof dateTimeIntervals = "ms", -): Date { - return new Date(x.getTime() - value * dateTimeIntervals[span]); -} diff --git a/packages/backend/src/prelude/url.ts b/packages/backend/src/prelude/url.ts deleted file mode 100644 index 9e3f3f7c12..0000000000 --- a/packages/backend/src/prelude/url.ts +++ /dev/null @@ -1,15 +0,0 @@ -export function query(obj: Record<string, unknown>): string { - const params = Object.entries(obj) - .filter(([, v]) => (Array.isArray(v) ? v.length : v !== undefined)) - .reduce((a, [k, v]) => ((a[k] = v), a), {} as Record<string, any>); - - return Object.entries(params) - .map((e) => `${e[0]}=${encodeURIComponent(e[1])}`) - .join("&"); -} - -export function appendQuery(url: string, query: string): string { - return `${url}${ - /\?/.test(url) ? (url.endsWith("?") ? "" : "&") : "?" - }${query}`; -} diff --git a/packages/backend/src/prelude/xml.ts b/packages/backend/src/prelude/xml.ts deleted file mode 100644 index 9dcc4c96fd..0000000000 --- a/packages/backend/src/prelude/xml.ts +++ /dev/null @@ -1,38 +0,0 @@ -const map: Record<string, string> = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'", -}; - -const beginingOfCDATA = "<![CDATA["; -const endOfCDATA = "]]>"; - -export function escapeValue(x: string): string { - let insideOfCDATA = false; - let builder = ""; - for (let i = 0; i < x.length; ) { - if (insideOfCDATA) { - if (x.slice(i, i + beginingOfCDATA.length) === beginingOfCDATA) { - insideOfCDATA = true; - i += beginingOfCDATA.length; - } else { - builder += x[i++]; - } - } else { - if (x.slice(i, i + endOfCDATA.length) === endOfCDATA) { - insideOfCDATA = false; - i += endOfCDATA.length; - } else { - const b = x[i++]; - builder += map[b] || b; - } - } - } - return builder; -} - -export function escapeAttribute(x: string): string { - return Object.entries(map).reduce((a, [k, v]) => a.replace(k, v), x); -} diff --git a/packages/backend/src/queue/get-job-info.ts b/packages/backend/src/queue/get-job-info.ts deleted file mode 100644 index ae3532cdae..0000000000 --- a/packages/backend/src/queue/get-job-info.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type Bull from "bull"; - -export function getJobInfo(job: Bull.Job, increment = false) { - const age = Date.now() - job.timestamp; - - const formated = - age > 60000 - ? `${Math.floor(age / 1000 / 60)}m` - : age > 10000 - ? `${Math.floor(age / 1000)}s` - : `${age}ms`; - - // onActiveとかonCompletedのattemptsMadeがなぜか0始まりなのでインクリメントする - const currentAttempts = job.attemptsMade + (increment ? 1 : 0); - const maxAttempts = job.opts ? job.opts.attempts : 0; - - return `id=${job.id} attempts=${currentAttempts}/${maxAttempts} age=${formated}`; -} diff --git a/packages/backend/src/queue/index.ts b/packages/backend/src/queue/index.ts deleted file mode 100644 index 035556e487..0000000000 --- a/packages/backend/src/queue/index.ts +++ /dev/null @@ -1,545 +0,0 @@ -import type httpSignature from "@peertube/http-signature"; -import { v4 as uuid } from "uuid"; - -import config from "@/config/index.js"; -import type { DriveFile } from "@/models/entities/drive-file.js"; -import type { IActivity } from "@/remote/activitypub/type.js"; -import type { Webhook, webhookEventTypes } from "@/models/entities/webhook.js"; -import { envOption } from "../env.js"; - -import processDeliver from "./processors/deliver.js"; -import processInbox from "./processors/inbox.js"; -import processDb from "./processors/db/index.js"; -import processObjectStorage from "./processors/object-storage/index.js"; -import processSystemQueue from "./processors/system/index.js"; -import processWebhookDeliver from "./processors/webhook-deliver.js"; -import processBackground from "./processors/background/index.js"; -import { endedPollNotification } from "./processors/ended-poll-notification.js"; -import { queueLogger } from "./logger.js"; -import { getJobInfo } from "./get-job-info.js"; -import { - systemQueue, - dbQueue, - deliverQueue, - inboxQueue, - objectStorageQueue, - endedPollNotificationQueue, - webhookDeliverQueue, - backgroundQueue, -} from "./queues.js"; -import type { ThinUser } from "./types.js"; - -function renderError(e: Error): any { - return { - stack: e.stack, - message: e.message, - name: e.name, - }; -} - -const systemLogger = queueLogger.createSubLogger("system"); -const deliverLogger = queueLogger.createSubLogger("deliver"); -const webhookLogger = queueLogger.createSubLogger("webhook"); -const inboxLogger = queueLogger.createSubLogger("inbox"); -const dbLogger = queueLogger.createSubLogger("db"); -const objectStorageLogger = queueLogger.createSubLogger("objectStorage"); - -systemQueue - .on("waiting", (jobId) => systemLogger.debug(`waiting id=${jobId}`)) - .on("active", (job) => systemLogger.debug(`active id=${job.id}`)) - .on("completed", (job, result) => - systemLogger.debug(`completed(${result}) id=${job.id}`), - ) - .on("failed", (job, err) => - systemLogger.warn(`failed(${err}) id=${job.id}`, { - job, - e: renderError(err), - }), - ) - .on("error", (job: any, err: Error) => - systemLogger.error(`error ${err}`, { job, e: renderError(err) }), - ) - .on("stalled", (job) => systemLogger.warn(`stalled id=${job.id}`)); - -deliverQueue - .on("waiting", (jobId) => deliverLogger.debug(`waiting id=${jobId}`)) - .on("active", (job) => - deliverLogger.debug(`active ${getJobInfo(job, true)} to=${job.data.to}`), - ) - .on("completed", (job, result) => - deliverLogger.debug( - `completed(${result}) ${getJobInfo(job, true)} to=${job.data.to}`, - ), - ) - .on("failed", (job, err) => - deliverLogger.warn(`failed(${err}) ${getJobInfo(job)} to=${job.data.to}`), - ) - .on("error", (job: any, err: Error) => - deliverLogger.error(`error ${err}`, { job, e: renderError(err) }), - ) - .on("stalled", (job) => - deliverLogger.warn(`stalled ${getJobInfo(job)} to=${job.data.to}`), - ); - -inboxQueue - .on("waiting", (jobId) => inboxLogger.debug(`waiting id=${jobId}`)) - .on("active", (job) => inboxLogger.debug(`active ${getJobInfo(job, true)}`)) - .on("completed", (job, result) => - inboxLogger.debug(`completed(${result}) ${getJobInfo(job, true)}`), - ) - .on("failed", (job, err) => - inboxLogger.warn( - `failed(${err}) ${getJobInfo(job)} activity=${ - job.data.activity ? job.data.activity.id : "none" - }`, - { job, e: renderError(err) }, - ), - ) - .on("error", (job: any, err: Error) => - inboxLogger.error(`error ${err}`, { job, e: renderError(err) }), - ) - .on("stalled", (job) => - inboxLogger.warn( - `stalled ${getJobInfo(job)} activity=${ - job.data.activity ? job.data.activity.id : "none" - }`, - ), - ); - -dbQueue - .on("waiting", (jobId) => dbLogger.debug(`waiting id=${jobId}`)) - .on("active", (job) => dbLogger.debug(`active id=${job.id}`)) - .on("completed", (job, result) => - dbLogger.debug(`completed(${result}) id=${job.id}`), - ) - .on("failed", (job, err) => - dbLogger.warn(`failed(${err}) id=${job.id}`, { job, e: renderError(err) }), - ) - .on("error", (job: any, err: Error) => - dbLogger.error(`error ${err}`, { job, e: renderError(err) }), - ) - .on("stalled", (job) => dbLogger.warn(`stalled id=${job.id}`)); - -objectStorageQueue - .on("waiting", (jobId) => objectStorageLogger.debug(`waiting id=${jobId}`)) - .on("active", (job) => objectStorageLogger.debug(`active id=${job.id}`)) - .on("completed", (job, result) => - objectStorageLogger.debug(`completed(${result}) id=${job.id}`), - ) - .on("failed", (job, err) => - objectStorageLogger.warn(`failed(${err}) id=${job.id}`, { - job, - e: renderError(err), - }), - ) - .on("error", (job: any, err: Error) => - objectStorageLogger.error(`error ${err}`, { job, e: renderError(err) }), - ) - .on("stalled", (job) => objectStorageLogger.warn(`stalled id=${job.id}`)); - -webhookDeliverQueue - .on("waiting", (jobId) => webhookLogger.debug(`waiting id=${jobId}`)) - .on("active", (job) => - webhookLogger.debug(`active ${getJobInfo(job, true)} to=${job.data.to}`), - ) - .on("completed", (job, result) => - webhookLogger.debug( - `completed(${result}) ${getJobInfo(job, true)} to=${job.data.to}`, - ), - ) - .on("failed", (job, err) => - webhookLogger.warn(`failed(${err}) ${getJobInfo(job)} to=${job.data.to}`), - ) - .on("error", (job: any, err: Error) => - webhookLogger.error(`error ${err}`, { job, e: renderError(err) }), - ) - .on("stalled", (job) => - webhookLogger.warn(`stalled ${getJobInfo(job)} to=${job.data.to}`), - ); - -export function deliver(user: ThinUser, content: unknown, to: string | null) { - if (content == null) return null; - if (to == null) return null; - - const data = { - user: { - id: user.id, - }, - content, - to, - }; - - return deliverQueue.add(data, { - attempts: config.deliverJobMaxAttempts || 12, - timeout: 1 * 60 * 1000, // 1min - backoff: { - type: "apBackoff", - }, - removeOnComplete: true, - removeOnFail: true, - }); -} - -export function inbox( - activity: IActivity, - signature: httpSignature.IParsedSignature, -) { - const data = { - activity: activity, - signature, - }; - - return inboxQueue.add(data, { - attempts: config.inboxJobMaxAttempts || 8, - timeout: 5 * 60 * 1000, // 5min - backoff: { - type: "apBackoff", - }, - removeOnComplete: true, - removeOnFail: true, - }); -} - -export function createDeleteDriveFilesJob(user: ThinUser) { - return dbQueue.add( - "deleteDriveFiles", - { - user: user, - }, - { - removeOnComplete: true, - removeOnFail: true, - }, - ); -} - -export function createExportCustomEmojisJob(user: ThinUser) { - return dbQueue.add( - "exportCustomEmojis", - { - user: user, - }, - { - removeOnComplete: true, - removeOnFail: true, - }, - ); -} - -export function createExportNotesJob(user: ThinUser) { - return dbQueue.add( - "exportNotes", - { - user: user, - }, - { - removeOnComplete: true, - removeOnFail: true, - }, - ); -} - -export function createExportFollowingJob( - user: ThinUser, - excludeMuting = false, - excludeInactive = false, -) { - return dbQueue.add( - "exportFollowing", - { - user: user, - excludeMuting, - excludeInactive, - }, - { - removeOnComplete: true, - removeOnFail: true, - }, - ); -} - -export function createExportMuteJob(user: ThinUser) { - return dbQueue.add( - "exportMute", - { - user: user, - }, - { - removeOnComplete: true, - removeOnFail: true, - }, - ); -} - -export function createExportBlockingJob(user: ThinUser) { - return dbQueue.add( - "exportBlocking", - { - user: user, - }, - { - removeOnComplete: true, - removeOnFail: true, - }, - ); -} - -export function createExportUserListsJob(user: ThinUser) { - return dbQueue.add( - "exportUserLists", - { - user: user, - }, - { - removeOnComplete: true, - removeOnFail: true, - }, - ); -} - -export function createImportFollowingJob( - user: ThinUser, - fileId: DriveFile["id"], -) { - return dbQueue.add( - "importFollowing", - { - user: user, - fileId: fileId, - }, - { - removeOnComplete: true, - removeOnFail: true, - }, - ); -} - -export function createImportPostsJob( - user: ThinUser, - fileId: DriveFile["id"], - signatureCheck: boolean, -) { - return dbQueue.add( - "importPosts", - { - user: user, - fileId: fileId, - signatureCheck: signatureCheck, - }, - { - removeOnComplete: true, - removeOnFail: true, - }, - ); -} - -export function createImportMutingJob(user: ThinUser, fileId: DriveFile["id"]) { - return dbQueue.add( - "importMuting", - { - user: user, - fileId: fileId, - }, - { - removeOnComplete: true, - removeOnFail: true, - }, - ); -} - -export function createImportBlockingJob( - user: ThinUser, - fileId: DriveFile["id"], -) { - return dbQueue.add( - "importBlocking", - { - user: user, - fileId: fileId, - }, - { - removeOnComplete: true, - removeOnFail: true, - }, - ); -} - -export function createImportUserListsJob( - user: ThinUser, - fileId: DriveFile["id"], -) { - return dbQueue.add( - "importUserLists", - { - user: user, - fileId: fileId, - }, - { - removeOnComplete: true, - removeOnFail: true, - }, - ); -} - -export function createImportCustomEmojisJob( - user: ThinUser, - fileId: DriveFile["id"], -) { - return dbQueue.add( - "importCustomEmojis", - { - user: user, - fileId: fileId, - }, - { - removeOnComplete: true, - removeOnFail: true, - }, - ); -} - -export function createDeleteAccountJob( - user: ThinUser, - opts: { soft?: boolean } = {}, -) { - return dbQueue.add( - "deleteAccount", - { - user: user, - soft: opts.soft, - }, - { - removeOnComplete: true, - removeOnFail: true, - }, - ); -} - -export function createDeleteObjectStorageFileJob(key: string) { - return objectStorageQueue.add( - "deleteFile", - { - key: key, - }, - { - removeOnComplete: true, - removeOnFail: true, - }, - ); -} - -export function createCleanRemoteFilesJob() { - return objectStorageQueue.add( - "cleanRemoteFiles", - {}, - { - removeOnComplete: true, - removeOnFail: true, - }, - ); -} - -export function createIndexAllNotesJob(data = {}) { - return backgroundQueue.add("indexAllNotes", data, { - removeOnComplete: true, - removeOnFail: true, - }); -} - -export function webhookDeliver( - webhook: Webhook, - type: typeof webhookEventTypes[number], - content: unknown, -) { - const data = { - type, - content, - webhookId: webhook.id, - userId: webhook.userId, - to: webhook.url, - secret: webhook.secret, - createdAt: Date.now(), - eventId: uuid(), - }; - - return webhookDeliverQueue.add(data, { - attempts: 4, - timeout: 1 * 60 * 1000, // 1min - backoff: { - type: "apBackoff", - }, - removeOnComplete: true, - removeOnFail: true, - }); -} - -export default function () { - if (envOption.onlyServer) return; - - deliverQueue.process(config.deliverJobConcurrency || 128, processDeliver); - inboxQueue.process(config.inboxJobConcurrency || 16, processInbox); - endedPollNotificationQueue.process(endedPollNotification); - webhookDeliverQueue.process(64, processWebhookDeliver); - processDb(dbQueue); - processObjectStorage(objectStorageQueue); - processBackground(backgroundQueue); - - systemQueue.add( - "tickCharts", - {}, - { - repeat: { cron: "55 * * * *" }, - removeOnComplete: true, - }, - ); - - systemQueue.add( - "resyncCharts", - {}, - { - repeat: { cron: "0 0 * * *" }, - removeOnComplete: true, - }, - ); - - systemQueue.add( - "cleanCharts", - {}, - { - repeat: { cron: "0 0 * * *" }, - removeOnComplete: true, - }, - ); - - systemQueue.add( - "clean", - {}, - { - repeat: { cron: "0 0 * * *" }, - removeOnComplete: true, - }, - ); - - systemQueue.add( - "checkExpiredMutings", - {}, - { - repeat: { cron: "*/5 * * * *" }, - removeOnComplete: true, - }, - ); - - processSystemQueue(systemQueue); -} - -export function destroy() { - deliverQueue.once("cleaned", (jobs, status) => { - deliverLogger.succ(`Cleaned ${jobs.length} ${status} jobs`); - }); - deliverQueue.clean(0, "delayed"); - - inboxQueue.once("cleaned", (jobs, status) => { - inboxLogger.succ(`Cleaned ${jobs.length} ${status} jobs`); - }); - inboxQueue.clean(0, "delayed"); -} diff --git a/packages/backend/src/queue/initialize.ts b/packages/backend/src/queue/initialize.ts deleted file mode 100644 index d7945d5dad..0000000000 --- a/packages/backend/src/queue/initialize.ts +++ /dev/null @@ -1,37 +0,0 @@ -import Bull from "bull"; -import config from "@/config/index.js"; - -export function initialize<T>(name: string, limitPerSec = -1) { - return new Bull<T>(name, { - redis: { - port: config.redis.port, - host: config.redis.host, - family: config.redis.family == null ? 0 : config.redis.family, - password: config.redis.pass, - db: config.redis.db || 0, - }, - prefix: config.redis.prefix ? `${config.redis.prefix}:queue` : "queue", - limiter: - limitPerSec > 0 - ? { - max: limitPerSec, - duration: 1000, - } - : undefined, - settings: { - backoffStrategies: { - apBackoff, - }, - }, - }); -} - -// ref. https://github.com/misskey-dev/misskey/pull/7635#issue-971097019 -function apBackoff(attemptsMade: number, err: Error) { - const baseDelay = 60 * 1000; // 1min - const maxBackoff = 8 * 60 * 60 * 1000; // 8hours - let backoff = (Math.pow(2, attemptsMade) - 1) * baseDelay; - backoff = Math.min(backoff, maxBackoff); - backoff += Math.round(backoff * Math.random() * 0.2); - return backoff; -} diff --git a/packages/backend/src/queue/logger.ts b/packages/backend/src/queue/logger.ts deleted file mode 100644 index 929c207e3c..0000000000 --- a/packages/backend/src/queue/logger.ts +++ /dev/null @@ -1,3 +0,0 @@ -import Logger from "@/services/logger.js"; - -export const queueLogger = new Logger("queue", "orange"); diff --git a/packages/backend/src/queue/processors/background/index-all-notes.ts b/packages/backend/src/queue/processors/background/index-all-notes.ts deleted file mode 100644 index 03219199d9..0000000000 --- a/packages/backend/src/queue/processors/background/index-all-notes.ts +++ /dev/null @@ -1,79 +0,0 @@ -import type Bull from "bull"; - -import { queueLogger } from "../../logger.js"; -import { Notes } from "@/models/index.js"; -import { MoreThan } from "typeorm"; -import { index } from "@/services/note/create.js"; -import { Note } from "@/models/entities/note.js"; - -const logger = queueLogger.createSubLogger("index-all-notes"); - -export default async function indexAllNotes( - job: Bull.Job<Record<string, unknown>>, - done: () => void, -): Promise<void> { - logger.info("Indexing all notes..."); - - let cursor: string | null = (job.data.cursor as string) ?? null; - let indexedCount: number = (job.data.indexedCount as number) ?? 0; - let total: number = (job.data.total as number) ?? 0; - - let running = true; - const take = 50000; - const batch = 100; - while (running) { - logger.info( - `Querying for ${take} notes ${indexedCount}/${ - total ? total : "?" - } at ${cursor}`, - ); - - let notes: Note[] = []; - try { - notes = await Notes.find({ - where: { - ...(cursor ? { id: MoreThan(cursor) } : {}), - }, - take: take, - order: { - id: 1, - }, - }); - } catch (e) { - logger.error(`Failed to query notes ${e}`); - continue; - } - - if (notes.length === 0) { - job.progress(100); - running = false; - break; - } - - try { - const count = await Notes.count(); - total = count; - job.update({ indexedCount, cursor, total }); - } catch (e) {} - - for (let i = 0; i < notes.length; i += batch) { - const chunk = notes.slice(i, i + batch); - await Promise.all(chunk.map((note) => index(note))); - - indexedCount += chunk.length; - const pct = (indexedCount / total) * 100; - job.update({ indexedCount, cursor, total }); - job.progress(+pct.toFixed(1)); - logger.info(`Indexed notes ${indexedCount}/${total ? total : "?"}`); - } - cursor = notes[notes.length - 1].id; - job.update({ indexedCount, cursor, total }); - - if (notes.length < take) { - running = false; - } - } - - done(); - logger.info("All notes have been indexed."); -} diff --git a/packages/backend/src/queue/processors/background/index.ts b/packages/backend/src/queue/processors/background/index.ts deleted file mode 100644 index 6674f954b0..0000000000 --- a/packages/backend/src/queue/processors/background/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type Bull from "bull"; -import indexAllNotes from "./index-all-notes.js"; - -const jobs = { - indexAllNotes, -} as Record<string, Bull.ProcessCallbackFunction<Record<string, unknown>>>; - -export default function (q: Bull.Queue) { - for (const [k, v] of Object.entries(jobs)) { - q.process(k, 16, v); - } -} diff --git a/packages/backend/src/queue/processors/db/delete-account.ts b/packages/backend/src/queue/processors/db/delete-account.ts deleted file mode 100644 index 764b83db2d..0000000000 --- a/packages/backend/src/queue/processors/db/delete-account.ts +++ /dev/null @@ -1,102 +0,0 @@ -import type Bull from "bull"; -import { queueLogger } from "../../logger.js"; -import { DriveFiles, Notes, UserProfiles, Users } from "@/models/index.js"; -import type { DbUserDeleteJobData } from "@/queue/types.js"; -import type { Note } from "@/models/entities/note.js"; -import type { DriveFile } from "@/models/entities/drive-file.js"; -import { MoreThan } from "typeorm"; -import { deleteFileSync } from "@/services/drive/delete-file.js"; -import { sendEmail } from "@/services/send-email.js"; - -const logger = queueLogger.createSubLogger("delete-account"); - -export async function deleteAccount( - job: Bull.Job<DbUserDeleteJobData>, -): Promise<string | void> { - logger.info(`Deleting account of ${job.data.user.id} ...`); - - const user = await Users.findOneBy({ id: job.data.user.id }); - if (user == null) { - return; - } - - { - // Delete notes - let cursor: Note["id"] | null = null; - - while (true) { - const notes = (await Notes.find({ - where: { - userId: user.id, - ...(cursor ? { id: MoreThan(cursor) } : {}), - }, - take: 100, - order: { - id: 1, - }, - })) as Note[]; - - if (notes.length === 0) { - break; - } - - cursor = notes[notes.length - 1].id; - - await Notes.delete(notes.map((note) => note.id)); - } - - logger.succ("All of notes deleted"); - } - - { - // Delete files - let cursor: DriveFile["id"] | null = null; - - while (true) { - const files = (await DriveFiles.find({ - where: { - userId: user.id, - ...(cursor ? { id: MoreThan(cursor) } : {}), - }, - take: 10, - order: { - id: 1, - }, - })) as DriveFile[]; - - if (files.length === 0) { - break; - } - - cursor = files[files.length - 1].id; - - for (const file of files) { - await deleteFileSync(file); - } - } - - logger.succ("All of files deleted"); - } - - { - // Send email notification - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - if (profile.email && profile.emailVerified) { - sendEmail( - profile.email, - "Account deleted", - "Your account has been deleted.", - "Your account has been deleted.", - ); - } - } - - // soft指定されている場合は物理削除しない - if (job.data.soft) { - // nop - } else { - await Users.delete(job.data.user.id); - } - - return "Account deleted"; -} diff --git a/packages/backend/src/queue/processors/db/delete-drive-files.ts b/packages/backend/src/queue/processors/db/delete-drive-files.ts deleted file mode 100644 index 28e4771329..0000000000 --- a/packages/backend/src/queue/processors/db/delete-drive-files.ts +++ /dev/null @@ -1,61 +0,0 @@ -import type Bull from "bull"; - -import { queueLogger } from "../../logger.js"; -import { deleteFileSync } from "@/services/drive/delete-file.js"; -import { Users, DriveFiles } from "@/models/index.js"; -import { MoreThan } from "typeorm"; -import type { DbUserJobData } from "@/queue/types.js"; - -const logger = queueLogger.createSubLogger("delete-drive-files"); - -export async function deleteDriveFiles( - job: Bull.Job<DbUserJobData>, - done: any, -): Promise<void> { - logger.info(`Deleting drive files of ${job.data.user.id} ...`); - - const user = await Users.findOneBy({ id: job.data.user.id }); - if (user == null) { - done(); - return; - } - - let deletedCount = 0; - let cursor: any = null; - - while (true) { - const files = await DriveFiles.find({ - where: { - userId: user.id, - ...(cursor ? { id: MoreThan(cursor) } : {}), - }, - take: 100, - order: { - id: 1, - }, - }); - - if (files.length === 0) { - job.progress(100); - break; - } - - cursor = files[files.length - 1].id; - - for (const file of files) { - await deleteFileSync(file); - deletedCount++; - } - - const total = await DriveFiles.countBy({ - userId: user.id, - }); - - job.progress(deletedCount / total); - } - - logger.succ( - `All drive files (${deletedCount}) of ${user.id} has been deleted.`, - ); - done(); -} diff --git a/packages/backend/src/queue/processors/db/export-blocking.ts b/packages/backend/src/queue/processors/db/export-blocking.ts deleted file mode 100644 index 90da76b872..0000000000 --- a/packages/backend/src/queue/processors/db/export-blocking.ts +++ /dev/null @@ -1,105 +0,0 @@ -import type Bull from "bull"; -import * as fs from "node:fs"; - -import { queueLogger } from "../../logger.js"; -import { addFile } from "@/services/drive/add-file.js"; -import { format as dateFormat } from "date-fns"; -import { getFullApAccount } from "@/misc/convert-host.js"; -import { createTemp } from "@/misc/create-temp.js"; -import { Users, Blockings } from "@/models/index.js"; -import { MoreThan } from "typeorm"; -import type { DbUserJobData } from "@/queue/types.js"; - -const logger = queueLogger.createSubLogger("export-blocking"); - -export async function exportBlocking( - job: Bull.Job<DbUserJobData>, - done: any, -): Promise<void> { - logger.info(`Exporting blocking of ${job.data.user.id} ...`); - - const user = await Users.findOneBy({ id: job.data.user.id }); - if (user == null) { - done(); - return; - } - - // Create temp file - const [path, cleanup] = await createTemp(); - - logger.info(`Temp file is ${path}`); - - try { - const stream = fs.createWriteStream(path, { flags: "a" }); - - let exportedCount = 0; - let cursor: any = null; - - while (true) { - const blockings = await Blockings.find({ - where: { - blockerId: user.id, - ...(cursor ? { id: MoreThan(cursor) } : {}), - }, - take: 100, - order: { - id: 1, - }, - }); - - if (blockings.length === 0) { - job.progress(100); - break; - } - - cursor = blockings[blockings.length - 1].id; - - for (const block of blockings) { - const u = await Users.findOneBy({ id: block.blockeeId }); - if (u == null) { - exportedCount++; - continue; - } - - const content = getFullApAccount(u.username, u.host); - await new Promise<void>((res, rej) => { - stream.write(content + "\n", (err) => { - if (err) { - logger.error(err); - rej(err); - } else { - res(); - } - }); - }); - exportedCount++; - } - - const total = await Blockings.countBy({ - blockerId: user.id, - }); - - job.progress(exportedCount / total); - } - - stream.end(); - logger.succ(`Exported to: ${path}`); - - const fileName = `blocking-${dateFormat( - new Date(), - "yyyy-MM-dd-HH-mm-ss", - )}.csv`; - const driveFile = await addFile({ - user, - path, - name: fileName, - force: true, - }); - - logger.succ(`Exported to: ${driveFile.id}`); - } finally { - cleanup(); - } - - done(); -} diff --git a/packages/backend/src/queue/processors/db/export-custom-emojis.ts b/packages/backend/src/queue/processors/db/export-custom-emojis.ts deleted file mode 100644 index 7a19d0b60b..0000000000 --- a/packages/backend/src/queue/processors/db/export-custom-emojis.ts +++ /dev/null @@ -1,130 +0,0 @@ -import type Bull from "bull"; -import * as fs from "node:fs"; - -import { ulid } from "ulid"; -import mime from "mime-types"; -import archiver from "archiver"; -import { queueLogger } from "../../logger.js"; -import { addFile } from "@/services/drive/add-file.js"; -import { format as dateFormat } from "date-fns"; -import { Users, Emojis } from "@/models/index.js"; -import {} from "@/queue/types.js"; -import { createTemp, createTempDir } from "@/misc/create-temp.js"; -import { downloadUrl } from "@/misc/download-url.js"; -import config from "@/config/index.js"; -import { IsNull } from "typeorm"; - -const logger = queueLogger.createSubLogger("export-custom-emojis"); - -export async function exportCustomEmojis( - job: Bull.Job, - done: () => void, -): Promise<void> { - logger.info("Exporting custom emojis ..."); - - const user = await Users.findOneBy({ id: job.data.user.id }); - if (user == null) { - done(); - return; - } - - const [path, cleanup] = await createTempDir(); - - logger.info(`Temp dir is ${path}`); - - const metaPath = `${path}/meta.json`; - - fs.writeFileSync(metaPath, "", "utf-8"); - - const metaStream = fs.createWriteStream(metaPath, { flags: "a" }); - - const writeMeta = (text: string): Promise<void> => { - return new Promise<void>((res, rej) => { - metaStream.write(text, (err) => { - if (err) { - logger.error(err); - rej(err); - } else { - res(); - } - }); - }); - }; - - await writeMeta( - `{"metaVersion":2,"host":"${ - config.host - }","exportedAt":"${new Date().toString()}","emojis":[`, - ); - - const customEmojis = await Emojis.find({ - where: { - host: IsNull(), - }, - order: { - id: "ASC", - }, - }); - - for (const emoji of customEmojis) { - const ext = mime.extension(emoji.type); - const fileName = emoji.name + (ext ? `.${ext}` : ""); - const emojiPath = `${path}/${fileName}`; - fs.writeFileSync(emojiPath, "", "binary"); - let downloaded = false; - - try { - await downloadUrl(emoji.originalUrl, emojiPath); - downloaded = true; - } catch (e) { - // TODO: 何度か再試行 - logger.error(e instanceof Error ? e : new Error(e as string)); - } - - if (!downloaded) { - fs.unlinkSync(emojiPath); - } - - const content = JSON.stringify({ - fileName: fileName, - downloaded: downloaded, - emoji: emoji, - }); - const isFirst = customEmojis.indexOf(emoji) === 0; - - await writeMeta(isFirst ? content : ",\n" + content); - } - - await writeMeta("]}"); - - metaStream.end(); - - // Create archive - const [archivePath, archiveCleanup] = await createTemp(); - const archiveStream = fs.createWriteStream(archivePath); - const archive = archiver("zip", { - zlib: { level: 0 }, - }); - archiveStream.on("close", async () => { - logger.succ(`Exported to: ${archivePath}`); - - const fileName = `custom-emojis-${dateFormat( - new Date(), - "yyyy-MM-dd-HH-mm-ss", - )}.zip`; - const driveFile = await addFile({ - user, - path: archivePath, - name: fileName, - force: true, - }); - - logger.succ(`Exported to: ${driveFile.id}`); - cleanup(); - archiveCleanup(); - done(); - }); - archive.pipe(archiveStream); - archive.directory(path, false); - archive.finalize(); -} diff --git a/packages/backend/src/queue/processors/db/export-following.ts b/packages/backend/src/queue/processors/db/export-following.ts deleted file mode 100644 index 80e8e6b925..0000000000 --- a/packages/backend/src/queue/processors/db/export-following.ts +++ /dev/null @@ -1,113 +0,0 @@ -import type Bull from "bull"; -import * as fs from "node:fs"; - -import { queueLogger } from "../../logger.js"; -import { addFile } from "@/services/drive/add-file.js"; -import { format as dateFormat } from "date-fns"; -import { getFullApAccount } from "@/misc/convert-host.js"; -import { createTemp } from "@/misc/create-temp.js"; -import { Users, Followings, Mutings } from "@/models/index.js"; -import { In, MoreThan, Not } from "typeorm"; -import type { DbUserJobData } from "@/queue/types.js"; -import type { Following } from "@/models/entities/following.js"; - -const logger = queueLogger.createSubLogger("export-following"); - -export async function exportFollowing( - job: Bull.Job<DbUserJobData>, - done: () => void, -): Promise<void> { - logger.info(`Exporting following of ${job.data.user.id} ...`); - - const user = await Users.findOneBy({ id: job.data.user.id }); - if (user == null) { - done(); - return; - } - - // Create temp file - const [path, cleanup] = await createTemp(); - - logger.info(`Temp file is ${path}`); - - try { - const stream = fs.createWriteStream(path, { flags: "a" }); - - let cursor: Following["id"] | null = null; - - const mutings = job.data.excludeMuting - ? await Mutings.findBy({ - muterId: user.id, - }) - : []; - - while (true) { - const followings = (await Followings.find({ - where: { - followerId: user.id, - ...(mutings.length > 0 - ? { followeeId: Not(In(mutings.map((x) => x.muteeId))) } - : {}), - ...(cursor ? { id: MoreThan(cursor) } : {}), - }, - take: 100, - order: { - id: 1, - }, - })) as Following[]; - - if (followings.length === 0) { - break; - } - - cursor = followings[followings.length - 1].id; - - for (const following of followings) { - const u = await Users.findOneBy({ id: following.followeeId }); - if (u == null) { - continue; - } - - if ( - job.data.excludeInactive && - u.updatedAt && - Date.now() - u.updatedAt.getTime() > 1000 * 60 * 60 * 24 * 90 - ) { - continue; - } - - const content = getFullApAccount(u.username, u.host); - await new Promise<void>((res, rej) => { - stream.write(content + "\n", (err) => { - if (err) { - logger.error(err); - rej(err); - } else { - res(); - } - }); - }); - } - } - - stream.end(); - logger.succ(`Exported to: ${path}`); - - const fileName = `following-${dateFormat( - new Date(), - "yyyy-MM-dd-HH-mm-ss", - )}.csv`; - const driveFile = await addFile({ - user, - path, - name: fileName, - force: true, - }); - - logger.succ(`Exported to: ${driveFile.id}`); - } finally { - cleanup(); - } - - done(); -} diff --git a/packages/backend/src/queue/processors/db/export-mute.ts b/packages/backend/src/queue/processors/db/export-mute.ts deleted file mode 100644 index 87b140b762..0000000000 --- a/packages/backend/src/queue/processors/db/export-mute.ts +++ /dev/null @@ -1,106 +0,0 @@ -import type Bull from "bull"; -import * as fs from "node:fs"; - -import { queueLogger } from "../../logger.js"; -import { addFile } from "@/services/drive/add-file.js"; -import { format as dateFormat } from "date-fns"; -import { getFullApAccount } from "@/misc/convert-host.js"; -import { createTemp } from "@/misc/create-temp.js"; -import { Users, Mutings } from "@/models/index.js"; -import { IsNull, MoreThan } from "typeorm"; -import type { DbUserJobData } from "@/queue/types.js"; - -const logger = queueLogger.createSubLogger("export-mute"); - -export async function exportMute( - job: Bull.Job<DbUserJobData>, - done: any, -): Promise<void> { - logger.info(`Exporting mute of ${job.data.user.id} ...`); - - const user = await Users.findOneBy({ id: job.data.user.id }); - if (user == null) { - done(); - return; - } - - // Create temp file - const [path, cleanup] = await createTemp(); - - logger.info(`Temp file is ${path}`); - - try { - const stream = fs.createWriteStream(path, { flags: "a" }); - - let exportedCount = 0; - let cursor: any = null; - - while (true) { - const mutes = await Mutings.find({ - where: { - muterId: user.id, - expiresAt: IsNull(), - ...(cursor ? { id: MoreThan(cursor) } : {}), - }, - take: 100, - order: { - id: 1, - }, - }); - - if (mutes.length === 0) { - job.progress(100); - break; - } - - cursor = mutes[mutes.length - 1].id; - - for (const mute of mutes) { - const u = await Users.findOneBy({ id: mute.muteeId }); - if (u == null) { - exportedCount++; - continue; - } - - const content = getFullApAccount(u.username, u.host); - await new Promise<void>((res, rej) => { - stream.write(content + "\n", (err) => { - if (err) { - logger.error(err); - rej(err); - } else { - res(); - } - }); - }); - exportedCount++; - } - - const total = await Mutings.countBy({ - muterId: user.id, - }); - - job.progress(exportedCount / total); - } - - stream.end(); - logger.succ(`Exported to: ${path}`); - - const fileName = `mute-${dateFormat( - new Date(), - "yyyy-MM-dd-HH-mm-ss", - )}.csv`; - const driveFile = await addFile({ - user, - path, - name: fileName, - force: true, - }); - - logger.succ(`Exported to: ${driveFile.id}`); - } finally { - cleanup(); - } - - done(); -} diff --git a/packages/backend/src/queue/processors/db/export-notes.ts b/packages/backend/src/queue/processors/db/export-notes.ts deleted file mode 100644 index de8fac05b4..0000000000 --- a/packages/backend/src/queue/processors/db/export-notes.ts +++ /dev/null @@ -1,132 +0,0 @@ -import type Bull from "bull"; -import * as fs from "node:fs"; - -import { queueLogger } from "../../logger.js"; -import { addFile } from "@/services/drive/add-file.js"; -import { format as dateFormat } from "date-fns"; -import { Users, Notes, Polls } from "@/models/index.js"; -import { MoreThan } from "typeorm"; -import type { Note } from "@/models/entities/note.js"; -import type { Poll } from "@/models/entities/poll.js"; -import type { DbUserJobData } from "@/queue/types.js"; -import { createTemp } from "@/misc/create-temp.js"; - -const logger = queueLogger.createSubLogger("export-notes"); - -export async function exportNotes( - job: Bull.Job<DbUserJobData>, - done: any, -): Promise<void> { - logger.info(`Exporting notes of ${job.data.user.id} ...`); - - const user = await Users.findOneBy({ id: job.data.user.id }); - if (user == null) { - done(); - return; - } - - // Create temp file - const [path, cleanup] = await createTemp(); - - logger.info(`Temp file is ${path}`); - - try { - const stream = fs.createWriteStream(path, { flags: "a" }); - - const write = (text: string): Promise<void> => { - return new Promise<void>((res, rej) => { - stream.write(text, (err) => { - if (err) { - logger.error(err); - rej(err); - } else { - res(); - } - }); - }); - }; - - await write("["); - - let exportedNotesCount = 0; - let cursor: Note["id"] | null = null; - - while (true) { - const notes = (await Notes.find({ - where: { - userId: user.id, - ...(cursor ? { id: MoreThan(cursor) } : {}), - }, - take: 100, - order: { - id: 1, - }, - })) as Note[]; - - if (notes.length === 0) { - job.progress(100); - break; - } - - cursor = notes[notes.length - 1].id; - - for (const note of notes) { - let poll: Poll | undefined; - if (note.hasPoll) { - poll = await Polls.findOneByOrFail({ noteId: note.id }); - } - const content = JSON.stringify(serialize(note, poll)); - const isFirst = exportedNotesCount === 0; - await write(isFirst ? content : ",\n" + content); - exportedNotesCount++; - } - - const total = await Notes.countBy({ - userId: user.id, - }); - - job.progress(exportedNotesCount / total); - } - - await write("]"); - - stream.end(); - logger.succ(`Exported to: ${path}`); - - const fileName = `notes-${dateFormat( - new Date(), - "yyyy-MM-dd-HH-mm-ss", - )}.json`; - const driveFile = await addFile({ - user, - path, - name: fileName, - force: true, - }); - - logger.succ(`Exported to: ${driveFile.id}`); - } finally { - cleanup(); - } - - done(); -} - -function serialize( - note: Note, - poll: Poll | null = null, -): Record<string, unknown> { - return { - id: note.id, - text: note.text, - createdAt: note.createdAt, - fileIds: note.fileIds, - replyId: note.replyId, - renoteId: note.renoteId, - poll: poll, - cw: note.cw, - visibility: note.visibility, - visibleUserIds: note.visibleUserIds, - localOnly: note.localOnly, - }; -} diff --git a/packages/backend/src/queue/processors/db/export-user-lists.ts b/packages/backend/src/queue/processors/db/export-user-lists.ts deleted file mode 100644 index e0c9cd8f3f..0000000000 --- a/packages/backend/src/queue/processors/db/export-user-lists.ts +++ /dev/null @@ -1,81 +0,0 @@ -import type Bull from "bull"; -import * as fs from "node:fs"; - -import { queueLogger } from "../../logger.js"; -import { addFile } from "@/services/drive/add-file.js"; -import { format as dateFormat } from "date-fns"; -import { getFullApAccount } from "@/misc/convert-host.js"; -import { createTemp } from "@/misc/create-temp.js"; -import { Users, UserLists, UserListJoinings } from "@/models/index.js"; -import { In } from "typeorm"; -import type { DbUserJobData } from "@/queue/types.js"; - -const logger = queueLogger.createSubLogger("export-user-lists"); - -export async function exportUserLists( - job: Bull.Job<DbUserJobData>, - done: any, -): Promise<void> { - logger.info(`Exporting user lists of ${job.data.user.id} ...`); - - const user = await Users.findOneBy({ id: job.data.user.id }); - if (user == null) { - done(); - return; - } - - const lists = await UserLists.findBy({ - userId: user.id, - }); - - // Create temp file - const [path, cleanup] = await createTemp(); - - logger.info(`Temp file is ${path}`); - - try { - const stream = fs.createWriteStream(path, { flags: "a" }); - - for (const list of lists) { - const joinings = await UserListJoinings.findBy({ userListId: list.id }); - const users = await Users.findBy({ - id: In(joinings.map((j) => j.userId)), - }); - - for (const u of users) { - const acct = getFullApAccount(u.username, u.host); - const content = `${list.name},${acct}`; - await new Promise<void>((res, rej) => { - stream.write(content + "\n", (err) => { - if (err) { - logger.error(err); - rej(err); - } else { - res(); - } - }); - }); - } - } - - stream.end(); - logger.succ(`Exported to: ${path}`); - - const fileName = `user-lists-${dateFormat( - new Date(), - "yyyy-MM-dd-HH-mm-ss", - )}.csv`; - const driveFile = await addFile({ - user, - path, - name: fileName, - force: true, - }); - - logger.succ(`Exported to: ${driveFile.id}`); - } finally { - cleanup(); - } - - done(); -} diff --git a/packages/backend/src/queue/processors/db/import-blocking.ts b/packages/backend/src/queue/processors/db/import-blocking.ts deleted file mode 100644 index 2fdf80a6eb..0000000000 --- a/packages/backend/src/queue/processors/db/import-blocking.ts +++ /dev/null @@ -1,79 +0,0 @@ -import type Bull from "bull"; - -import { queueLogger } from "../../logger.js"; -import * as Acct from "@/misc/acct.js"; -import { resolveUser } from "@/remote/resolve-user.js"; -import { downloadTextFile } from "@/misc/download-text-file.js"; -import { isSelfHost, toPuny } from "@/misc/convert-host.js"; -import { Users, DriveFiles, Blockings } from "@/models/index.js"; -import type { DbUserImportJobData } from "@/queue/types.js"; -import block from "@/services/blocking/create.js"; -import { IsNull } from "typeorm"; - -const logger = queueLogger.createSubLogger("import-blocking"); - -export async function importBlocking( - job: Bull.Job<DbUserImportJobData>, - done: any, -): Promise<void> { - logger.info(`Importing blocking of ${job.data.user.id} ...`); - - const user = await Users.findOneBy({ id: job.data.user.id }); - if (user == null) { - done(); - return; - } - - const file = await DriveFiles.findOneBy({ - id: job.data.fileId, - }); - if (file == null) { - done(); - return; - } - - const csv = await downloadTextFile(file.url); - - let linenum = 0; - - for (const line of csv.trim().split("\n")) { - linenum++; - - try { - const acct = line.split(",")[0].trim(); - const { username, host } = Acct.parse(acct); - - let target = isSelfHost(host!) - ? await Users.findOneBy({ - host: IsNull(), - usernameLower: username.toLowerCase(), - }) - : await Users.findOneBy({ - host: toPuny(host!), - usernameLower: username.toLowerCase(), - }); - - if (host == null && target == null) continue; - - if (target == null) { - target = await resolveUser(username, host); - } - - if (target == null) { - throw new Error(`cannot resolve user: @${username}@${host}`); - } - - // skip myself - if (target.id === job.data.user.id) continue; - - logger.info(`Block[${linenum}] ${target.id} ...`); - - await block(user, target); - } catch (e) { - logger.warn(`Error in line:${linenum} ${e}`); - } - } - - logger.succ("Imported"); - done(); -} diff --git a/packages/backend/src/queue/processors/db/import-custom-emojis.ts b/packages/backend/src/queue/processors/db/import-custom-emojis.ts deleted file mode 100644 index 373a3a2daf..0000000000 --- a/packages/backend/src/queue/processors/db/import-custom-emojis.ts +++ /dev/null @@ -1,91 +0,0 @@ -import type Bull from "bull"; -import * as fs from "node:fs"; -import unzipper from "unzipper"; - -import { queueLogger } from "../../logger.js"; -import { createTempDir } from "@/misc/create-temp.js"; -import { downloadUrl } from "@/misc/download-url.js"; -import { DriveFiles, Emojis } from "@/models/index.js"; -import type { DbUserImportJobData } from "@/queue/types.js"; -import { addFile } from "@/services/drive/add-file.js"; -import { genId } from "@/misc/gen-id.js"; -import { db } from "@/db/postgre.js"; - -const logger = queueLogger.createSubLogger("import-custom-emojis"); - -// TODO: 名前衝突時の動作を選べるようにする -export async function importCustomEmojis( - job: Bull.Job<DbUserImportJobData>, - done: any, -): Promise<void> { - logger.info("Importing custom emojis ..."); - - const file = await DriveFiles.findOneBy({ - id: job.data.fileId, - }); - if (file == null) { - done(); - return; - } - - const [path, cleanup] = await createTempDir(); - - logger.info(`Temp dir is ${path}`); - - const destPath = `${path}/emojis.zip`; - - try { - fs.writeFileSync(destPath, "", "binary"); - await downloadUrl(file.url, destPath); - } catch (e) { - // TODO: 何度か再試行 - if (e instanceof Error || typeof e === "string") { - logger.error(e); - } - throw e; - } - - const outputPath = `${path}/emojis`; - const unzipStream = fs.createReadStream(destPath); - const extractor = unzipper.Extract({ path: outputPath }); - extractor.on("close", async () => { - const metaRaw = fs.readFileSync(`${outputPath}/meta.json`, "utf-8"); - const meta = JSON.parse(metaRaw); - - for (const record of meta.emojis) { - if (!record.downloaded) continue; - const emojiInfo = record.emoji; - const emojiPath = `${outputPath}/${record.fileName}`; - await Emojis.delete({ - name: emojiInfo.name, - }); - const driveFile = await addFile({ - user: null, - path: emojiPath, - name: record.fileName, - force: true, - }); - const emoji = await Emojis.insert({ - id: genId(), - updatedAt: new Date(), - name: emojiInfo.name, - category: emojiInfo.category, - host: null, - aliases: emojiInfo.aliases, - originalUrl: driveFile.url, - publicUrl: driveFile.webpublicUrl ?? driveFile.url, - type: driveFile.webpublicType ?? driveFile.type, - license: emojiInfo.license, - }).then((x) => Emojis.findOneByOrFail(x.identifiers[0])); - } - - await db.queryResultCache!.remove(["meta_emojis"]); - - cleanup(); - - logger.succ("Imported"); - done(); - }); - unzipStream.pipe(extractor); - logger.succ(`Unzipping to ${outputPath}`); -} diff --git a/packages/backend/src/queue/processors/db/import-following.ts b/packages/backend/src/queue/processors/db/import-following.ts deleted file mode 100644 index b1a7cd2c9b..0000000000 --- a/packages/backend/src/queue/processors/db/import-following.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { IsNull } from "typeorm"; -import follow from "@/services/following/create.js"; - -import * as Acct from "@/misc/acct.js"; -import { resolveUser } from "@/remote/resolve-user.js"; -import { downloadTextFile } from "@/misc/download-text-file.js"; -import { isSelfHost, toPuny } from "@/misc/convert-host.js"; -import { Users, DriveFiles } from "@/models/index.js"; -import type { DbUserImportJobData } from "@/queue/types.js"; -import { queueLogger } from "../../logger.js"; -import type Bull from "bull"; - -const logger = queueLogger.createSubLogger("import-following"); - -export async function importFollowing( - job: Bull.Job<DbUserImportJobData>, - done: any, -): Promise<void> { - logger.info(`Importing following of ${job.data.user.id} ...`); - - const user = await Users.findOneBy({ id: job.data.user.id }); - if (user == null) { - done(); - return; - } - - const file = await DriveFiles.findOneBy({ - id: job.data.fileId, - }); - if (file == null) { - done(); - return; - } - - const csv = await downloadTextFile(file.url); - - let linenum = 0; - - if (file.type.endsWith("json")) { - for (const acct of JSON.parse(csv)) { - try { - const { username, host } = Acct.parse(acct); - - let target = isSelfHost(host!) - ? await Users.findOneBy({ - host: IsNull(), - usernameLower: username.toLowerCase(), - }) - : await Users.findOneBy({ - host: toPuny(host!), - usernameLower: username.toLowerCase(), - }); - - if (host == null && target == null) continue; - - if (target == null) { - target = await resolveUser(username, host); - } - - if (target == null) { - throw new Error(`cannot resolve user: @${username}@${host}`); - } - - // skip myself - if (target.id === job.data.user.id) continue; - - logger.info(`Follow[${linenum}] ${target.id} ...`); - - follow(user, target); - } catch (e) { - logger.warn(`Error in line:${linenum} ${e}`); - } - } - } else { - for (const line of csv.trim().split("\n")) { - linenum++; - - try { - const acct = line.split(",")[0].trim(); - const { username, host } = Acct.parse(acct); - - let target = isSelfHost(host!) - ? await Users.findOneBy({ - host: IsNull(), - usernameLower: username.toLowerCase(), - }) - : await Users.findOneBy({ - host: toPuny(host!), - usernameLower: username.toLowerCase(), - }); - - if (host == null && target == null) continue; - - if (target == null) { - target = await resolveUser(username, host); - } - - if (target == null) { - throw new Error(`cannot resolve user: @${username}@${host}`); - } - - // skip myself - if (target.id === job.data.user.id) continue; - - logger.info(`Follow[${linenum}] ${target.id} ...`); - - follow(user, target); - } catch (e) { - logger.warn(`Error in line:${linenum} ${e}`); - } - } - } - - logger.succ("Imported"); - done(); -} diff --git a/packages/backend/src/queue/processors/db/import-muting.ts b/packages/backend/src/queue/processors/db/import-muting.ts deleted file mode 100644 index 80e0567397..0000000000 --- a/packages/backend/src/queue/processors/db/import-muting.ts +++ /dev/null @@ -1,89 +0,0 @@ -import type Bull from "bull"; - -import { queueLogger } from "../../logger.js"; -import * as Acct from "@/misc/acct.js"; -import { resolveUser } from "@/remote/resolve-user.js"; -import { downloadTextFile } from "@/misc/download-text-file.js"; -import { isSelfHost, toPuny } from "@/misc/convert-host.js"; -import { Users, DriveFiles, Mutings } from "@/models/index.js"; -import type { DbUserImportJobData } from "@/queue/types.js"; -import type { User } from "@/models/entities/user.js"; -import { genId } from "@/misc/gen-id.js"; -import { IsNull } from "typeorm"; - -const logger = queueLogger.createSubLogger("import-muting"); - -export async function importMuting( - job: Bull.Job<DbUserImportJobData>, - done: any, -): Promise<void> { - logger.info(`Importing muting of ${job.data.user.id} ...`); - - const user = await Users.findOneBy({ id: job.data.user.id }); - if (user == null) { - done(); - return; - } - - const file = await DriveFiles.findOneBy({ - id: job.data.fileId, - }); - if (file == null) { - done(); - return; - } - - const csv = await downloadTextFile(file.url); - - let linenum = 0; - - for (const line of csv.trim().split("\n")) { - linenum++; - - try { - const acct = line.split(",")[0].trim(); - const { username, host } = Acct.parse(acct); - - let target = isSelfHost(host!) - ? await Users.findOneBy({ - host: IsNull(), - usernameLower: username.toLowerCase(), - }) - : await Users.findOneBy({ - host: toPuny(host!), - usernameLower: username.toLowerCase(), - }); - - if (host == null && target == null) continue; - - if (target == null) { - target = await resolveUser(username, host); - } - - if (target == null) { - throw new Error(`cannot resolve user: @${username}@${host}`); - } - - // skip myself - if (target.id === job.data.user.id) continue; - - logger.info(`Mute[${linenum}] ${target.id} ...`); - - await mute(user, target); - } catch (e) { - logger.warn(`Error in line:${linenum} ${e}`); - } - } - - logger.succ("Imported"); - done(); -} - -async function mute(user: User, target: User) { - await Mutings.insert({ - id: genId(), - createdAt: new Date(), - muterId: user.id, - muteeId: target.id, - }); -} diff --git a/packages/backend/src/queue/processors/db/import-posts.ts b/packages/backend/src/queue/processors/db/import-posts.ts deleted file mode 100644 index 20ef3a518d..0000000000 --- a/packages/backend/src/queue/processors/db/import-posts.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { IsNull } from "typeorm"; -import follow from "@/services/following/create.js"; - -import * as Post from "@/misc/post.js"; -import create from "@/services/note/create.js"; -import { downloadTextFile } from "@/misc/download-text-file.js"; -import { Users, DriveFiles } from "@/models/index.js"; -import type { DbUserImportPostsJobData } from "@/queue/types.js"; -import { queueLogger } from "../../logger.js"; -import type Bull from "bull"; -import { htmlToMfm } from "@/remote/activitypub/misc/html-to-mfm.js"; - -const logger = queueLogger.createSubLogger("import-posts"); - -export async function importPosts( - job: Bull.Job<DbUserImportPostsJobData>, - done: any, -): Promise<void> { - logger.info(`Importing posts of ${job.data.user.id} ...`); - - const user = await Users.findOneBy({ id: job.data.user.id }); - if (user == null) { - done(); - return; - } - - const file = await DriveFiles.findOneBy({ - id: job.data.fileId, - }); - if (file == null) { - done(); - return; - } - - const json = await downloadTextFile(file.url); - - let linenum = 0; - - try { - const parsed = JSON.parse(json); - if (parsed instanceof Array) { - logger.info("Parsing key style posts"); - for (const post of JSON.parse(json)) { - try { - linenum++; - if (post.replyId != null) { - continue; - } - if (post.renoteId != null) { - continue; - } - if (post.visibility !== "public") { - continue; - } - const { text, cw, localOnly, createdAt } = Post.parse(post); - - logger.info(`Posting[${linenum}] ...`); - - const note = await create(user, { - createdAt: createdAt, - files: undefined, - poll: undefined, - text: text || undefined, - reply: null, - renote: null, - cw: cw, - localOnly, - visibility: "public", - visibleUsers: [], - channel: null, - apMentions: new Array(0), - apHashtags: undefined, - apEmojis: undefined, - }); - } catch (e) { - logger.warn(`Error in line:${linenum} ${e}`); - } - } - } else if (parsed instanceof Object) { - logger.info("Parsing animal style posts"); - for (const post of parsed.orderedItems) { - try { - linenum++; - if (post.object.inReplyTo != null) { - continue; - } - if (post.directMessage) { - continue; - } - if (job.data.signatureCheck) { - if (!post.signature) { - continue; - } - } - let text; - try { - text = htmlToMfm(post.object.content, post.object.tag); - } catch (e) { - continue; - } - logger.info(`Posting[${linenum}] ...`); - - const note = await create(user, { - createdAt: new Date(post.object.published), - files: undefined, - poll: undefined, - text: text || undefined, - reply: null, - renote: null, - cw: post.sensitive, - localOnly: false, - visibility: "public", - visibleUsers: [], - channel: null, - apMentions: new Array(0), - apHashtags: undefined, - apEmojis: undefined, - }); - } catch (e) { - logger.warn(`Error in line:${linenum} ${e}`); - } - } - } - } catch (e) { - // handle error - logger.warn(`Error reading: ${e}`); - } - - logger.succ("Imported"); - done(); -} diff --git a/packages/backend/src/queue/processors/db/import-user-lists.ts b/packages/backend/src/queue/processors/db/import-user-lists.ts deleted file mode 100644 index 0c23f06991..0000000000 --- a/packages/backend/src/queue/processors/db/import-user-lists.ts +++ /dev/null @@ -1,96 +0,0 @@ -import type Bull from "bull"; - -import { queueLogger } from "../../logger.js"; -import * as Acct from "@/misc/acct.js"; -import { resolveUser } from "@/remote/resolve-user.js"; -import { pushUserToUserList } from "@/services/user-list/push.js"; -import { downloadTextFile } from "@/misc/download-text-file.js"; -import { isSelfHost, toPuny } from "@/misc/convert-host.js"; -import { - DriveFiles, - Users, - UserLists, - UserListJoinings, -} from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import type { DbUserImportJobData } from "@/queue/types.js"; -import { IsNull } from "typeorm"; - -const logger = queueLogger.createSubLogger("import-user-lists"); - -export async function importUserLists( - job: Bull.Job<DbUserImportJobData>, - done: any, -): Promise<void> { - logger.info(`Importing user lists of ${job.data.user.id} ...`); - - const user = await Users.findOneBy({ id: job.data.user.id }); - if (user == null) { - done(); - return; - } - - const file = await DriveFiles.findOneBy({ - id: job.data.fileId, - }); - if (file == null) { - done(); - return; - } - - const csv = await downloadTextFile(file.url); - - let linenum = 0; - - for (const line of csv.trim().split("\n")) { - linenum++; - - try { - const listName = line.split(",")[0].trim(); - const { username, host } = Acct.parse(line.split(",")[1].trim()); - - let list = await UserLists.findOneBy({ - userId: user.id, - name: listName, - }); - - if (list == null) { - list = await UserLists.insert({ - id: genId(), - createdAt: new Date(), - userId: user.id, - name: listName, - }).then((x) => UserLists.findOneByOrFail(x.identifiers[0])); - } - - let target = isSelfHost(host!) - ? await Users.findOneBy({ - host: IsNull(), - usernameLower: username.toLowerCase(), - }) - : await Users.findOneBy({ - host: toPuny(host!), - usernameLower: username.toLowerCase(), - }); - - if (target == null) { - target = await resolveUser(username, host); - } - - if ( - (await UserListJoinings.findOneBy({ - userListId: list!.id, - userId: target.id, - })) != null - ) - continue; - - pushUserToUserList(target, list!); - } catch (e) { - logger.warn(`Error in line:${linenum} ${e}`); - } - } - - logger.succ("Imported"); - done(); -} diff --git a/packages/backend/src/queue/processors/db/index.ts b/packages/backend/src/queue/processors/db/index.ts deleted file mode 100644 index 22b55a3683..0000000000 --- a/packages/backend/src/queue/processors/db/index.ts +++ /dev/null @@ -1,43 +0,0 @@ -import type Bull from "bull"; -import type { DbJobData } from "@/queue/types.js"; -import { deleteDriveFiles } from "./delete-drive-files.js"; -import { exportCustomEmojis } from "./export-custom-emojis.js"; -import { exportNotes } from "./export-notes.js"; -import { exportFollowing } from "./export-following.js"; -import { exportMute } from "./export-mute.js"; -import { exportBlocking } from "./export-blocking.js"; -import { exportUserLists } from "./export-user-lists.js"; -import { importFollowing } from "./import-following.js"; -import { importUserLists } from "./import-user-lists.js"; -import { deleteAccount } from "./delete-account.js"; -import { importMuting } from "./import-muting.js"; -import { importPosts } from "./import-posts.js"; -import { importBlocking } from "./import-blocking.js"; -import { importCustomEmojis } from "./import-custom-emojis.js"; - -const jobs = { - deleteDriveFiles, - exportCustomEmojis, - exportNotes, - exportFollowing, - exportMute, - exportBlocking, - exportUserLists, - importFollowing, - importMuting, - importBlocking, - importUserLists, - importPosts, - importCustomEmojis, - deleteAccount, -} as Record< - string, - | Bull.ProcessCallbackFunction<DbJobData> - | Bull.ProcessPromiseFunction<DbJobData> ->; - -export default function (dbQueue: Bull.Queue<DbJobData>) { - for (const [k, v] of Object.entries(jobs)) { - dbQueue.process(k, v); - } -} diff --git a/packages/backend/src/queue/processors/deliver.ts b/packages/backend/src/queue/processors/deliver.ts deleted file mode 100644 index 65471a559f..0000000000 --- a/packages/backend/src/queue/processors/deliver.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { URL } from "node:url"; -import request from "@/remote/activitypub/request.js"; -import { registerOrFetchInstanceDoc } from "@/services/register-or-fetch-instance-doc.js"; -import Logger from "@/services/logger.js"; -import { Instances } from "@/models/index.js"; -import { - apRequestChart, - federationChart, - instanceChart, -} from "@/services/chart/index.js"; -import { fetchInstanceMetadata } from "@/services/fetch-instance-metadata.js"; -import { toPuny } from "@/misc/convert-host.js"; -import { StatusError } from "@/misc/fetch.js"; -import { shouldSkipInstance } from "@/misc/skipped-instances.js"; -import type { DeliverJobData } from "@/queue/types.js"; -import type Bull from "bull"; - -const logger = new Logger("deliver"); - -let latest: string | null = null; - -export default async (job: Bull.Job<DeliverJobData>) => { - const { host } = new URL(job.data.to); - const puny = toPuny(host); - - if (await shouldSkipInstance(puny)) return "skip"; - - try { - if (latest !== (latest = JSON.stringify(job.data.content, null, 2))) { - logger.debug(`delivering ${latest}`); - } - - await request(job.data.user, job.data.to, job.data.content); - - // Update stats - registerOrFetchInstanceDoc(host).then((i) => { - Instances.update(i.id, { - latestRequestSentAt: new Date(), - latestStatus: 200, - lastCommunicatedAt: new Date(), - isNotResponding: false, - }); - - fetchInstanceMetadata(i); - - instanceChart.requestSent(i.host, true); - apRequestChart.deliverSucc(); - federationChart.deliverd(i.host, true); - }); - - return "Success"; - } catch (res) { - // Update stats - registerOrFetchInstanceDoc(host).then((i) => { - Instances.update(i.id, { - latestRequestSentAt: new Date(), - latestStatus: res instanceof StatusError ? res.statusCode : null, - isNotResponding: true, - }); - - instanceChart.requestSent(i.host, false); - apRequestChart.deliverFail(); - federationChart.deliverd(i.host, false); - }); - - if (res instanceof StatusError) { - // 4xx - if (res.isClientError) { - // HTTPステータスコード4xxはクライアントエラーであり、それはつまり - // 何回再送しても成功することはないということなのでエラーにはしないでおく - return `${res.statusCode} ${res.statusMessage}`; - } - - // 5xx etc. - throw new Error(`${res.statusCode} ${res.statusMessage}`); - } else { - // DNS error, socket error, timeout ... - throw res; - } - } -}; diff --git a/packages/backend/src/queue/processors/ended-poll-notification.ts b/packages/backend/src/queue/processors/ended-poll-notification.ts deleted file mode 100644 index 9fe57d8da3..0000000000 --- a/packages/backend/src/queue/processors/ended-poll-notification.ts +++ /dev/null @@ -1,36 +0,0 @@ -import type Bull from "bull"; -import { In } from "typeorm"; -import { Notes, Polls, PollVotes } from "@/models/index.js"; -import { queueLogger } from "../logger.js"; -import type { EndedPollNotificationJobData } from "@/queue/types.js"; -import { createNotification } from "@/services/create-notification.js"; - -const logger = queueLogger.createSubLogger("ended-poll-notification"); - -export async function endedPollNotification( - job: Bull.Job<EndedPollNotificationJobData>, - done: any, -): Promise<void> { - const note = await Notes.findOneBy({ id: job.data.noteId }); - if (note == null || !note.hasPoll) { - done(); - return; - } - - const votes = await PollVotes.createQueryBuilder("vote") - .select("vote.userId") - .where("vote.noteId = :noteId", { noteId: note.id }) - .innerJoinAndSelect("vote.user", "user") - .andWhere("user.host IS NULL") - .getMany(); - - const userIds = [...new Set([note.userId, ...votes.map((v) => v.userId)])]; - - for (const userId of userIds) { - createNotification(userId, "pollEnded", { - noteId: note.id, - }); - } - - done(); -} diff --git a/packages/backend/src/queue/processors/inbox.ts b/packages/backend/src/queue/processors/inbox.ts deleted file mode 100644 index ca063a6f3f..0000000000 --- a/packages/backend/src/queue/processors/inbox.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { URL } from "node:url"; -import type Bull from "bull"; -import httpSignature from "@peertube/http-signature"; -import perform from "@/remote/activitypub/perform.js"; -import Logger from "@/services/logger.js"; -import { registerOrFetchInstanceDoc } from "@/services/register-or-fetch-instance-doc.js"; -import { Instances } from "@/models/index.js"; -import { - apRequestChart, - federationChart, - instanceChart, -} from "@/services/chart/index.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { toPuny, extractDbHost } from "@/misc/convert-host.js"; -import { getApId } from "@/remote/activitypub/type.js"; -import { fetchInstanceMetadata } from "@/services/fetch-instance-metadata.js"; -import type { InboxJobData } from "../types.js"; -import DbResolver from "@/remote/activitypub/db-resolver.js"; -import { resolvePerson } from "@/remote/activitypub/models/person.js"; -import { LdSignature } from "@/remote/activitypub/misc/ld-signature.js"; -import { StatusError } from "@/misc/fetch.js"; -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import type { UserPublickey } from "@/models/entities/user-publickey.js"; -import { shouldBlockInstance } from "@/misc/should-block-instance.js"; - -const logger = new Logger("inbox"); - -// Processing when an activity arrives in the user's inbox -export default async (job: Bull.Job<InboxJobData>): Promise<string> => { - const signature = job.data.signature; // HTTP-signature - const activity = job.data.activity; - - //#region Log - const info = Object.assign({}, activity) as any; - info["@context"] = undefined; - logger.debug(JSON.stringify(info, null, 2)); - //#endregion - const host = toPuny(new URL(signature.keyId).hostname); - - // interrupt if blocked - const meta = await fetchMeta(); - if (await shouldBlockInstance(host, meta)) { - return `Blocked request: ${host}`; - } - - // only whitelisted instances in private mode - if (meta.privateMode && !meta.allowedHosts.includes(host)) { - return `Blocked request: ${host}`; - } - - const keyIdLower = signature.keyId.toLowerCase(); - if (keyIdLower.startsWith("acct:")) { - return `Old keyId is no longer supported. ${keyIdLower}`; - } - - const dbResolver = new DbResolver(); - - // HTTP-Signature keyId from DB - let authUser: { - user: CacheableRemoteUser; - key: UserPublickey | null; - } | null = await dbResolver.getAuthUserFromKeyId(signature.keyId); - - // keyIdでわからなければ、activity.actorを元にDBから取得 || activity.actorを元にリモートから取得 - if (authUser == null) { - try { - authUser = await dbResolver.getAuthUserFromApId(getApId(activity.actor)); - } catch (e) { - // Skip if target is 4xx - if (e instanceof StatusError) { - if (e.isClientError) { - return `skip: Ignored deleted actors on both ends ${activity.actor} - ${e.statusCode}`; - } - throw new Error( - `Error in actor ${activity.actor} - ${e.statusCode || e}`, - ); - } - } - } - - // それでもわからなければ終了 - if (authUser == null) { - return "skip: failed to resolve user"; - } - - // publicKey がなくても終了 - if (authUser.key == null) { - return "skip: failed to resolve user publicKey"; - } - - // HTTP-Signatureの検証 - const httpSignatureValidated = httpSignature.verifySignature( - signature, - authUser.key.keyPem, - ); - - // また、signatureのsignerは、activity.actorと一致する必要がある - if (!httpSignatureValidated || authUser.user.uri !== activity.actor) { - // 一致しなくても、でもLD-Signatureがありそうならそっちも見る - if (activity.signature) { - if (activity.signature.type !== "RsaSignature2017") { - return `skip: unsupported LD-signature type ${activity.signature.type}`; - } - - // activity.signature.creator: https://example.oom/users/user#main-key - // みたいになっててUserを引っ張れば公開キーも入ることを期待する - if (activity.signature.creator) { - const candicate = activity.signature.creator.replace(/#.*/, ""); - await resolvePerson(candicate).catch(() => null); - } - - // keyIdからLD-Signatureのユーザーを取得 - authUser = await dbResolver.getAuthUserFromKeyId( - activity.signature.creator, - ); - if (authUser == null) { - return "skip: LD-Signatureのユーザーが取得できませんでした"; - } - - if (authUser.key == null) { - return "skip: LD-SignatureのユーザーはpublicKeyを持っていませんでした"; - } - - // LD-Signature検証 - const ldSignature = new LdSignature(); - const verified = await ldSignature - .verifyRsaSignature2017(activity, authUser.key.keyPem) - .catch(() => false); - if (!verified) { - return "skip: LD-Signatureの検証に失敗しました"; - } - - // もう一度actorチェック - if (authUser.user.uri !== activity.actor) { - return `skip: LD-Signature user(${authUser.user.uri}) !== activity.actor(${activity.actor})`; - } - - // ブロックしてたら中断 - const ldHost = extractDbHost(authUser.user.uri); - if (await shouldBlockInstance(ldHost, meta)) { - return `Blocked request: ${ldHost}`; - } - } else { - return `skip: http-signature verification failed and no LD-Signature. keyId=${signature.keyId}`; - } - } - - // activity.idがあればホストが署名者のホストであることを確認する - if (typeof activity.id === "string") { - const signerHost = extractDbHost(authUser.user.uri!); - const activityIdHost = extractDbHost(activity.id); - if (signerHost !== activityIdHost) { - return `skip: signerHost(${signerHost}) !== activity.id host(${activityIdHost}`; - } - } - - // Update stats - registerOrFetchInstanceDoc(authUser.user.host).then((i) => { - Instances.update(i.id, { - latestRequestReceivedAt: new Date(), - lastCommunicatedAt: new Date(), - isNotResponding: false, - }); - - fetchInstanceMetadata(i); - - instanceChart.requestReceived(i.host); - apRequestChart.inbox(); - federationChart.inbox(i.host); - }); - - // アクティビティを処理 - await perform(authUser.user, activity); - return "ok"; -}; diff --git a/packages/backend/src/queue/processors/object-storage/clean-remote-files.ts b/packages/backend/src/queue/processors/object-storage/clean-remote-files.ts deleted file mode 100644 index fdfe05d1a6..0000000000 --- a/packages/backend/src/queue/processors/object-storage/clean-remote-files.ts +++ /dev/null @@ -1,53 +0,0 @@ -import type Bull from "bull"; - -import { queueLogger } from "../../logger.js"; -import { deleteFileSync } from "@/services/drive/delete-file.js"; -import { DriveFiles } from "@/models/index.js"; -import { MoreThan, Not, IsNull } from "typeorm"; - -const logger = queueLogger.createSubLogger("clean-remote-files"); - -export default async function cleanRemoteFiles( - job: Bull.Job<Record<string, unknown>>, - done: any, -): Promise<void> { - logger.info("Deleting cached remote files..."); - - let deletedCount = 0; - let cursor: any = null; - - while (true) { - const files = await DriveFiles.find({ - where: { - userHost: Not(IsNull()), - isLink: false, - ...(cursor ? { id: MoreThan(cursor) } : {}), - }, - take: 8, - order: { - id: 1, - }, - }); - - if (files.length === 0) { - job.progress(100); - break; - } - - cursor = files[files.length - 1].id; - - await Promise.all(files.map((file) => deleteFileSync(file, true))); - - deletedCount += 8; - - const total = await DriveFiles.countBy({ - userHost: Not(IsNull()), - isLink: false, - }); - - job.progress(deletedCount / total); - } - - logger.succ("All cahced remote files has been deleted."); - done(); -} diff --git a/packages/backend/src/queue/processors/object-storage/delete-file.ts b/packages/backend/src/queue/processors/object-storage/delete-file.ts deleted file mode 100644 index 174aa1906c..0000000000 --- a/packages/backend/src/queue/processors/object-storage/delete-file.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { ObjectStorageFileJobData } from "@/queue/types.js"; -import type Bull from "bull"; -import { deleteObjectStorageFile } from "@/services/drive/delete-file.js"; - -export default async (job: Bull.Job<ObjectStorageFileJobData>) => { - const key: string = job.data.key; - - await deleteObjectStorageFile(key); - - return "Success"; -}; diff --git a/packages/backend/src/queue/processors/object-storage/index.ts b/packages/backend/src/queue/processors/object-storage/index.ts deleted file mode 100644 index 5f90d4cd09..0000000000 --- a/packages/backend/src/queue/processors/object-storage/index.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type Bull from "bull"; -import type { ObjectStorageJobData } from "@/queue/types.js"; -import deleteFile from "./delete-file.js"; -import cleanRemoteFiles from "./clean-remote-files.js"; - -const jobs = { - deleteFile, - cleanRemoteFiles, -} as Record< - string, - | Bull.ProcessCallbackFunction<ObjectStorageJobData> - | Bull.ProcessPromiseFunction<ObjectStorageJobData> ->; - -export default function (q: Bull.Queue) { - for (const [k, v] of Object.entries(jobs)) { - q.process(k, 16, v); - } -} diff --git a/packages/backend/src/queue/processors/system/check-expired-mutings.ts b/packages/backend/src/queue/processors/system/check-expired-mutings.ts deleted file mode 100644 index a482d0218a..0000000000 --- a/packages/backend/src/queue/processors/system/check-expired-mutings.ts +++ /dev/null @@ -1,33 +0,0 @@ -import type Bull from "bull"; -import { In } from "typeorm"; -import { Mutings } from "@/models/index.js"; -import { queueLogger } from "../../logger.js"; -import { publishUserEvent } from "@/services/stream.js"; - -const logger = queueLogger.createSubLogger("check-expired-mutings"); - -export async function checkExpiredMutings( - job: Bull.Job<Record<string, unknown>>, - done: any, -): Promise<void> { - logger.info("Checking expired mutings..."); - - const expired = await Mutings.createQueryBuilder("muting") - .where("muting.expiresAt IS NOT NULL") - .andWhere("muting.expiresAt < :now", { now: new Date() }) - .innerJoinAndSelect("muting.mutee", "mutee") - .getMany(); - - if (expired.length > 0) { - await Mutings.delete({ - id: In(expired.map((m) => m.id)), - }); - - for (const m of expired) { - publishUserEvent(m.muterId, "unmute", m.mutee!); - } - } - - logger.succ("All expired mutings checked."); - done(); -} diff --git a/packages/backend/src/queue/processors/system/clean-charts.ts b/packages/backend/src/queue/processors/system/clean-charts.ts deleted file mode 100644 index dde5d95fe3..0000000000 --- a/packages/backend/src/queue/processors/system/clean-charts.ts +++ /dev/null @@ -1,44 +0,0 @@ -import type Bull from "bull"; - -import { queueLogger } from "../../logger.js"; -import { - activeUsersChart, - driveChart, - federationChart, - hashtagChart, - instanceChart, - notesChart, - perUserDriveChart, - perUserFollowingChart, - perUserNotesChart, - perUserReactionsChart, - usersChart, - apRequestChart, -} from "@/services/chart/index.js"; - -const logger = queueLogger.createSubLogger("clean-charts"); - -export async function cleanCharts( - job: Bull.Job<Record<string, unknown>>, - done: any, -): Promise<void> { - logger.info("Clean charts..."); - - await Promise.all([ - federationChart.clean(), - notesChart.clean(), - usersChart.clean(), - activeUsersChart.clean(), - instanceChart.clean(), - perUserNotesChart.clean(), - driveChart.clean(), - perUserReactionsChart.clean(), - hashtagChart.clean(), - perUserFollowingChart.clean(), - perUserDriveChart.clean(), - apRequestChart.clean(), - ]); - - logger.succ("All charts successfully cleaned."); - done(); -} diff --git a/packages/backend/src/queue/processors/system/clean.ts b/packages/backend/src/queue/processors/system/clean.ts deleted file mode 100644 index fbd45b0bb9..0000000000 --- a/packages/backend/src/queue/processors/system/clean.ts +++ /dev/null @@ -1,21 +0,0 @@ -import type Bull from "bull"; -import { LessThan } from "typeorm"; -import { UserIps } from "@/models/index.js"; - -import { queueLogger } from "../../logger.js"; - -const logger = queueLogger.createSubLogger("clean"); - -export async function clean( - job: Bull.Job<Record<string, unknown>>, - done: any, -): Promise<void> { - logger.info("Cleaning..."); - - UserIps.delete({ - createdAt: LessThan(new Date(Date.now() - 1000 * 60 * 60 * 24 * 90)), - }); - - logger.succ("Cleaned."); - done(); -} diff --git a/packages/backend/src/queue/processors/system/index.ts b/packages/backend/src/queue/processors/system/index.ts deleted file mode 100644 index 68833d76f4..0000000000 --- a/packages/backend/src/queue/processors/system/index.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type Bull from "bull"; -import { tickCharts } from "./tick-charts.js"; -import { resyncCharts } from "./resync-charts.js"; -import { cleanCharts } from "./clean-charts.js"; -import { checkExpiredMutings } from "./check-expired-mutings.js"; -import { clean } from "./clean.js"; - -const jobs = { - tickCharts, - resyncCharts, - cleanCharts, - checkExpiredMutings, - clean, -} as Record< - string, - | Bull.ProcessCallbackFunction<Record<string, unknown>> - | Bull.ProcessPromiseFunction<Record<string, unknown>> ->; - -export default function (dbQueue: Bull.Queue<Record<string, unknown>>) { - for (const [k, v] of Object.entries(jobs)) { - dbQueue.process(k, v); - } -} diff --git a/packages/backend/src/queue/processors/system/resync-charts.ts b/packages/backend/src/queue/processors/system/resync-charts.ts deleted file mode 100644 index dbea0df733..0000000000 --- a/packages/backend/src/queue/processors/system/resync-charts.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type Bull from "bull"; - -import { queueLogger } from "../../logger.js"; -import { driveChart, notesChart, usersChart } from "@/services/chart/index.js"; - -const logger = queueLogger.createSubLogger("resync-charts"); - -export async function resyncCharts( - job: Bull.Job<Record<string, unknown>>, - done: any, -): Promise<void> { - logger.info("Resync charts..."); - - // TODO: ユーザーごとのチャートも更新する - // TODO: インスタンスごとのチャートも更新する - await Promise.all([ - driveChart.resync(), - notesChart.resync(), - usersChart.resync(), - ]); - - logger.succ("All charts successfully resynced."); - done(); -} diff --git a/packages/backend/src/queue/processors/system/tick-charts.ts b/packages/backend/src/queue/processors/system/tick-charts.ts deleted file mode 100644 index 33eed8a596..0000000000 --- a/packages/backend/src/queue/processors/system/tick-charts.ts +++ /dev/null @@ -1,44 +0,0 @@ -import type Bull from "bull"; - -import { queueLogger } from "../../logger.js"; -import { - activeUsersChart, - driveChart, - federationChart, - hashtagChart, - instanceChart, - notesChart, - perUserDriveChart, - perUserFollowingChart, - perUserNotesChart, - perUserReactionsChart, - usersChart, - apRequestChart, -} from "@/services/chart/index.js"; - -const logger = queueLogger.createSubLogger("tick-charts"); - -export async function tickCharts( - job: Bull.Job<Record<string, unknown>>, - done: any, -): Promise<void> { - logger.info("Tick charts..."); - - await Promise.all([ - federationChart.tick(false), - notesChart.tick(false), - usersChart.tick(false), - activeUsersChart.tick(false), - instanceChart.tick(false), - perUserNotesChart.tick(false), - driveChart.tick(false), - perUserReactionsChart.tick(false), - hashtagChart.tick(false), - perUserFollowingChart.tick(false), - perUserDriveChart.tick(false), - apRequestChart.tick(false), - ]); - - logger.succ("All charts successfully ticked."); - done(); -} diff --git a/packages/backend/src/queue/processors/webhook-deliver.ts b/packages/backend/src/queue/processors/webhook-deliver.ts deleted file mode 100644 index 0a54ae7d89..0000000000 --- a/packages/backend/src/queue/processors/webhook-deliver.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { URL } from "node:url"; -import type Bull from "bull"; -import Logger from "@/services/logger.js"; -import type { WebhookDeliverJobData } from "../types.js"; -import { getResponse, StatusError } from "@/misc/fetch.js"; -import { Webhooks } from "@/models/index.js"; -import config from "@/config/index.js"; - -const logger = new Logger("webhook"); - -export default async (job: Bull.Job<WebhookDeliverJobData>) => { - try { - logger.debug(`delivering ${job.data.webhookId}`); - - const res = await getResponse({ - url: job.data.to, - method: "POST", - headers: { - "User-Agent": "Calckey-Hooks", - "X-Calckey-Host": config.host, - "X-Calckey-Hook-Id": job.data.webhookId, - "X-Calckey-Hook-Secret": job.data.secret, - "Content-Type": "application/json", - }, - body: JSON.stringify({ - hookId: job.data.webhookId, - userId: job.data.userId, - eventId: job.data.eventId, - createdAt: job.data.createdAt, - type: job.data.type, - body: job.data.content, - }), - }); - - Webhooks.update( - { id: job.data.webhookId }, - { - latestSentAt: new Date(), - latestStatus: res.status, - }, - ); - - return "Success"; - } catch (res) { - Webhooks.update( - { id: job.data.webhookId }, - { - latestSentAt: new Date(), - latestStatus: res instanceof StatusError ? res.statusCode : 1, - }, - ); - - if (res instanceof StatusError) { - // 4xx - if (res.isClientError) { - return `${res.statusCode} ${res.statusMessage}`; - } - - // 5xx etc. - throw new Error(`${res.statusCode} ${res.statusMessage}`); - } else { - // DNS error, socket error, timeout ... - throw res; - } - } -}; diff --git a/packages/backend/src/queue/queues.ts b/packages/backend/src/queue/queues.ts deleted file mode 100644 index 6d7fffcb30..0000000000 --- a/packages/backend/src/queue/queues.ts +++ /dev/null @@ -1,41 +0,0 @@ -import config from "@/config/index.js"; -import { initialize as initializeQueue } from "./initialize.js"; -import type { - DeliverJobData, - InboxJobData, - DbJobData, - ObjectStorageJobData, - EndedPollNotificationJobData, - WebhookDeliverJobData, -} from "./types.js"; - -export const systemQueue = initializeQueue<Record<string, unknown>>("system"); -export const endedPollNotificationQueue = - initializeQueue<EndedPollNotificationJobData>("endedPollNotification"); -export const deliverQueue = initializeQueue<DeliverJobData>( - "deliver", - config.deliverJobPerSec || 128, -); -export const inboxQueue = initializeQueue<InboxJobData>( - "inbox", - config.inboxJobPerSec || 16, -); -export const dbQueue = initializeQueue<DbJobData>("db"); -export const objectStorageQueue = - initializeQueue<ObjectStorageJobData>("objectStorage"); -export const webhookDeliverQueue = initializeQueue<WebhookDeliverJobData>( - "webhookDeliver", - 64, -); -export const backgroundQueue = initializeQueue<Record<string, unknown>>("bg"); - -export const queues = [ - systemQueue, - endedPollNotificationQueue, - deliverQueue, - inboxQueue, - dbQueue, - objectStorageQueue, - webhookDeliverQueue, - backgroundQueue, -]; diff --git a/packages/backend/src/queue/types.ts b/packages/backend/src/queue/types.ts deleted file mode 100644 index e31619ff27..0000000000 --- a/packages/backend/src/queue/types.ts +++ /dev/null @@ -1,75 +0,0 @@ -import type { DriveFile } from "@/models/entities/drive-file.js"; -import type { Note } from "@/models/entities/note"; -import type { User } from "@/models/entities/user.js"; -import type { Webhook } from "@/models/entities/webhook"; -import type { IActivity } from "@/remote/activitypub/type.js"; -import type httpSignature from "@peertube/http-signature"; - -export type DeliverJobData = { - /** Actor */ - user: ThinUser; - /** Activity */ - content: unknown; - /** inbox URL to deliver */ - to: string; -}; - -export type InboxJobData = { - activity: IActivity; - signature: httpSignature.IParsedSignature; -}; - -export type DbJobData = - | DbUserJobData - | DbUserImportPostsJobData - | DbUserImportJobData - | DbUserDeleteJobData; - -export type DbUserJobData = { - user: ThinUser; - excludeMuting: boolean; - excludeInactive: boolean; -}; - -export type DbUserDeleteJobData = { - user: ThinUser; - soft?: boolean; -}; - -export type DbUserImportJobData = { - user: ThinUser; - fileId: DriveFile["id"]; -}; - -export type DbUserImportPostsJobData = { - user: ThinUser; - fileId: DriveFile["id"]; - signatureCheck: boolean; -}; - -export type ObjectStorageJobData = - | ObjectStorageFileJobData - | Record<string, unknown>; - -export type ObjectStorageFileJobData = { - key: string; -}; - -export type EndedPollNotificationJobData = { - noteId: Note["id"]; -}; - -export type WebhookDeliverJobData = { - type: string; - content: unknown; - webhookId: Webhook["id"]; - userId: User["id"]; - to: string; - secret: string; - createdAt: number; - eventId: string; -}; - -export type ThinUser = { - id: User["id"]; -}; diff --git a/packages/backend/src/remote/activitypub/ap-request.ts b/packages/backend/src/remote/activitypub/ap-request.ts deleted file mode 100644 index d5a9ec0539..0000000000 --- a/packages/backend/src/remote/activitypub/ap-request.ts +++ /dev/null @@ -1,152 +0,0 @@ -import * as crypto from "node:crypto"; -import { URL } from "node:url"; - -type Request = { - url: string; - method: string; - headers: Record<string, string>; -}; - -type PrivateKey = { - privateKeyPem: string; - keyId: string; -}; - -export function createSignedPost(args: { - key: PrivateKey; - url: string; - body: string; - additionalHeaders: Record<string, string>; -}) { - const u = new URL(args.url); - const digestHeader = `SHA-256=${crypto - .createHash("sha256") - .update(args.body) - .digest("base64")}`; - - const request: Request = { - url: u.href, - method: "POST", - headers: objectAssignWithLcKey( - { - Date: new Date().toUTCString(), - Host: u.hostname, - "Content-Type": "application/activity+json", - Digest: digestHeader, - }, - args.additionalHeaders, - ), - }; - - const result = signToRequest(request, args.key, [ - "(request-target)", - "date", - "host", - "digest", - ]); - - return { - request, - signingString: result.signingString, - signature: result.signature, - signatureHeader: result.signatureHeader, - }; -} - -export function createSignedGet(args: { - key: PrivateKey; - url: string; - additionalHeaders: Record<string, string>; -}) { - const u = new URL(args.url); - - const request: Request = { - url: u.href, - method: "GET", - headers: objectAssignWithLcKey( - { - Accept: "application/activity+json, application/ld+json", - Date: new Date().toUTCString(), - Host: new URL(args.url).hostname, - }, - args.additionalHeaders, - ), - }; - - const result = signToRequest(request, args.key, [ - "(request-target)", - "date", - "host", - "accept", - ]); - - return { - request, - signingString: result.signingString, - signature: result.signature, - signatureHeader: result.signatureHeader, - }; -} - -function signToRequest( - request: Request, - key: PrivateKey, - includeHeaders: string[], -) { - const signingString = genSigningString(request, includeHeaders); - const signature = crypto - .sign("sha256", Buffer.from(signingString), key.privateKeyPem) - .toString("base64"); - const signatureHeader = `keyId="${ - key.keyId - }",algorithm="rsa-sha256",headers="${includeHeaders.join( - " ", - )}",signature="${signature}"`; - - request.headers = objectAssignWithLcKey(request.headers, { - Signature: signatureHeader, - }); - - return { - request, - signingString, - signature, - signatureHeader, - }; -} - -function genSigningString(request: Request, includeHeaders: string[]) { - request.headers = lcObjectKey(request.headers); - - const results: string[] = []; - - for (const key of includeHeaders.map((x) => x.toLowerCase())) { - if (key === "(request-target)") { - results.push( - `(request-target): ${request.method.toLowerCase()} ${ - new URL(request.url).pathname - }`, - ); - } else { - results.push(`${key}: ${request.headers[key]}`); - } - } - - return results.join("\n"); -} - -function lcObjectKey(src: Record<string, string>) { - const dst: Record<string, string> = {}; - for (const key of Object.keys(src).filter( - (x) => x !== "__proto__" && typeof src[x] === "string", - )) - dst[key.toLowerCase()] = src[key]; - return dst; -} - -function objectAssignWithLcKey( - a: Record<string, string>, - b: Record<string, string>, -) { - return Object.assign(lcObjectKey(a), lcObjectKey(b)); -} diff --git a/packages/backend/src/remote/activitypub/audience.ts b/packages/backend/src/remote/activitypub/audience.ts deleted file mode 100644 index 210d47573c..0000000000 --- a/packages/backend/src/remote/activitypub/audience.ts +++ /dev/null @@ -1,104 +0,0 @@ -import type { ApObject } from "./type.js"; -import { getApIds } from "./type.js"; -import type Resolver from "./resolver.js"; -import { resolvePerson } from "./models/person.js"; -import { unique, concat } from "@/prelude/array.js"; -import promiseLimit from "promise-limit"; -import type { - CacheableRemoteUser, - CacheableUser, -} from "@/models/entities/user.js"; -import { User } from "@/models/entities/user.js"; - -type Visibility = "public" | "home" | "followers" | "specified"; - -type AudienceInfo = { - visibility: Visibility; - mentionedUsers: CacheableUser[]; - visibleUsers: CacheableUser[]; -}; - -export async function parseAudience( - actor: CacheableRemoteUser, - to?: ApObject, - cc?: ApObject, - resolver?: Resolver, -): Promise<AudienceInfo> { - const toGroups = groupingAudience(getApIds(to), actor); - const ccGroups = groupingAudience(getApIds(cc), actor); - - const others = unique(concat([toGroups.other, ccGroups.other])); - - const limit = promiseLimit<CacheableUser | null>(2); - const mentionedUsers = ( - await Promise.all( - others.map((id) => - limit(() => resolvePerson(id, resolver).catch(() => null)), - ), - ) - ).filter((x): x is CacheableUser => x != null); - - if (toGroups.public.length > 0) { - return { - visibility: "public", - mentionedUsers, - visibleUsers: [], - }; - } - - if (ccGroups.public.length > 0) { - return { - visibility: "home", - mentionedUsers, - visibleUsers: [], - }; - } - - if (toGroups.followers.length > 0) { - return { - visibility: "followers", - mentionedUsers, - visibleUsers: [], - }; - } - - return { - visibility: "specified", - mentionedUsers, - visibleUsers: mentionedUsers, - }; -} - -function groupingAudience(ids: string[], actor: CacheableRemoteUser) { - const groups = { - public: [] as string[], - followers: [] as string[], - other: [] as string[], - }; - - for (const id of ids) { - if (isPublic(id)) { - groups.public.push(id); - } else if (isFollowers(id, actor)) { - groups.followers.push(id); - } else { - groups.other.push(id); - } - } - - groups.other = unique(groups.other); - - return groups; -} - -function isPublic(id: string) { - return [ - "https://www.w3.org/ns/activitystreams#Public", - "as#Public", - "Public", - ].includes(id); -} - -function isFollowers(id: string, actor: CacheableRemoteUser) { - return id === (actor.followersUri || `${actor.uri}/followers`); -} diff --git a/packages/backend/src/remote/activitypub/check-fetch.ts b/packages/backend/src/remote/activitypub/check-fetch.ts deleted file mode 100644 index a8bbe61b84..0000000000 --- a/packages/backend/src/remote/activitypub/check-fetch.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { URL } from "url"; -import httpSignature from "@peertube/http-signature"; -import config from "@/config/index.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { toPuny } from "@/misc/convert-host.js"; -import DbResolver from "@/remote/activitypub/db-resolver.js"; -import { getApId } from "@/remote/activitypub/type.js"; -import { shouldBlockInstance } from "@/misc/should-block-instance.js"; -import type { IncomingMessage } from "http"; - -export async function hasSignature(req: IncomingMessage): Promise<string> { - const meta = await fetchMeta(); - const required = meta.secureMode || meta.privateMode; - - try { - httpSignature.parseRequest(req, { headers: [] }); - } catch (e) { - if (e instanceof Error && e.name === "MissingHeaderError") { - return required ? "missing" : "optional"; - } - return "invalid"; - } - return required ? "supplied" : "unneeded"; -} - -export async function checkFetch(req: IncomingMessage): Promise<number> { - const meta = await fetchMeta(); - if (meta.secureMode || meta.privateMode) { - let signature; - - try { - signature = httpSignature.parseRequest(req, { headers: [] }); - } catch (e) { - return 401; - } - - const keyId = new URL(signature.keyId); - const host = toPuny(keyId.hostname); - - if (await shouldBlockInstance(host, meta)) { - return 403; - } - - if ( - meta.privateMode && - host !== config.host && - !meta.allowedHosts.includes(host) - ) { - return 403; - } - - const keyIdLower = signature.keyId.toLowerCase(); - if (keyIdLower.startsWith("acct:")) { - // Old keyId is no longer supported. - return 401; - } - - const dbResolver = new DbResolver(); - - // HTTP-Signature keyIdを元にDBから取得 - let authUser = await dbResolver.getAuthUserFromKeyId(signature.keyId); - - // keyIdでわからなければ、resolveしてみる - if (authUser == null) { - try { - keyId.hash = ""; - authUser = await dbResolver.getAuthUserFromApId( - getApId(keyId.toString()), - ); - } catch (e) { - // できなければ駄目 - return 403; - } - } - - // publicKey がなくても終了 - if (authUser?.key == null) { - return 403; - } - - // もう一回チェック - if (authUser.user.host !== host) { - return 403; - } - - // HTTP-Signatureの検証 - const httpSignatureValidated = httpSignature.verifySignature( - signature, - authUser.key.keyPem, - ); - - if (!httpSignatureValidated) { - return 403; - } - } - return 200; -} diff --git a/packages/backend/src/remote/activitypub/db-resolver.ts b/packages/backend/src/remote/activitypub/db-resolver.ts deleted file mode 100644 index 0a2aec9e85..0000000000 --- a/packages/backend/src/remote/activitypub/db-resolver.ts +++ /dev/null @@ -1,189 +0,0 @@ -import escapeRegexp from "escape-regexp"; -import config from "@/config/index.js"; -import type { Note } from "@/models/entities/note.js"; -import type { - CacheableRemoteUser, - CacheableUser, -} from "@/models/entities/user.js"; -import { User, IRemoteUser } from "@/models/entities/user.js"; -import type { UserPublickey } from "@/models/entities/user-publickey.js"; -import type { MessagingMessage } from "@/models/entities/messaging-message.js"; -import { - Notes, - Users, - UserPublickeys, - MessagingMessages, -} from "@/models/index.js"; -import { Cache } from "@/misc/cache.js"; -import { uriPersonCache, userByIdCache } from "@/services/user-cache.js"; -import type { IObject } from "./type.js"; -import { getApId } from "./type.js"; -import { resolvePerson } from "./models/person.js"; - -const publicKeyCache = new Cache<UserPublickey | null>(Infinity); -const publicKeyByUserIdCache = new Cache<UserPublickey | null>(Infinity); - -export type UriParseResult = - | { - /** wether the URI was generated by us */ - local: true; - /** id in DB */ - id: string; - /** hint of type, e.g. "notes", "users" */ - type: string; - /** any remaining text after type and id, not including the slash after id. undefined if empty */ - rest?: string; - } - | { - /** wether the URI was generated by us */ - local: false; - /** uri in DB */ - uri: string; - }; - -export function parseUri(value: string | IObject): UriParseResult { - const uri = getApId(value); - - // the host part of a URL is case insensitive, so use the 'i' flag. - const localRegex = new RegExp( - `^${escapeRegexp(config.url)}/(\\w+)/(\\w+)(?:/(.+))?`, - "i", - ); - const matchLocal = uri.match(localRegex); - - if (matchLocal) { - return { - local: true, - type: matchLocal[1], - id: matchLocal[2], - rest: matchLocal[3], - }; - } else { - return { - local: false, - uri, - }; - } -} - -export default class DbResolver { - constructor() {} - - /** - * AP Note => Misskey Note in DB - */ - public async getNoteFromApId(value: string | IObject): Promise<Note | null> { - const parsed = parseUri(value); - - if (parsed.local) { - if (parsed.type !== "notes") return null; - - return await Notes.findOneBy({ - id: parsed.id, - }); - } else { - return await Notes.findOneBy({ - uri: parsed.uri, - }); - } - } - - public async getMessageFromApId( - value: string | IObject, - ): Promise<MessagingMessage | null> { - const parsed = parseUri(value); - - if (parsed.local) { - if (parsed.type !== "notes") return null; - - return await MessagingMessages.findOneBy({ - id: parsed.id, - }); - } else { - return await MessagingMessages.findOneBy({ - uri: parsed.uri, - }); - } - } - - /** - * AP Person => Misskey User in DB - */ - public async getUserFromApId( - value: string | IObject, - ): Promise<CacheableUser | null> { - const parsed = parseUri(value); - - if (parsed.local) { - if (parsed.type !== "users") return null; - - return ( - (await userByIdCache.fetchMaybe(parsed.id, () => - Users.findOneBy({ - id: parsed.id, - }).then((x) => x ?? undefined), - )) ?? null - ); - } else { - return await uriPersonCache.fetch(parsed.uri, () => - Users.findOneBy({ - uri: parsed.uri, - }), - ); - } - } - - /** - * AP KeyId => Misskey User and Key - */ - public async getAuthUserFromKeyId(keyId: string): Promise<{ - user: CacheableRemoteUser; - key: UserPublickey; - } | null> { - const key = await publicKeyCache.fetch( - keyId, - async () => { - const key = await UserPublickeys.findOneBy({ - keyId, - }); - - if (key == null) return null; - - return key; - }, - (key) => key != null, - ); - - if (key == null) return null; - - return { - user: (await userByIdCache.fetch(key.userId, () => - Users.findOneByOrFail({ id: key.userId }), - )) as CacheableRemoteUser, - key, - }; - } - - /** - * AP Actor id => Misskey User and Key - */ - public async getAuthUserFromApId(uri: string): Promise<{ - user: CacheableRemoteUser; - key: UserPublickey | null; - } | null> { - const user = (await resolvePerson(uri)) as CacheableRemoteUser; - - if (user == null) return null; - - const key = await publicKeyByUserIdCache.fetch( - user.id, - () => UserPublickeys.findOneBy({ userId: user.id }), - (v) => v != null, - ); - - return { - user, - key, - }; - } -} diff --git a/packages/backend/src/remote/activitypub/deliver-manager.ts b/packages/backend/src/remote/activitypub/deliver-manager.ts deleted file mode 100644 index 400e047774..0000000000 --- a/packages/backend/src/remote/activitypub/deliver-manager.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { IsNull, Not } from "typeorm"; -import { Users, Followings } from "@/models/index.js"; -import type { ILocalUser, IRemoteUser, User } from "@/models/entities/user.js"; -import { deliver } from "@/queue/index.js"; -import { skippedInstances } from "@/misc/skipped-instances.js"; - -//#region types -interface IRecipe { - type: string; -} - -interface IFollowersRecipe extends IRecipe { - type: "Followers"; -} - -interface IDirectRecipe extends IRecipe { - type: "Direct"; - to: IRemoteUser; -} - -const isFollowers = (recipe: any): recipe is IFollowersRecipe => - recipe.type === "Followers"; - -const isDirect = (recipe: any): recipe is IDirectRecipe => - recipe.type === "Direct"; -//#endregion - -export default class DeliverManager { - private actor: { id: User["id"]; host: null }; - private activity: any; - private recipes: IRecipe[] = []; - - /** - * Constructor - * @param actor Actor - * @param activity Activity to deliver - */ - constructor(actor: { id: User["id"]; host: null }, activity: any) { - this.actor = actor; - this.activity = activity; - } - - /** - * Add recipe for followers deliver - */ - public addFollowersRecipe() { - const deliver = { - type: "Followers", - } as IFollowersRecipe; - - this.addRecipe(deliver); - } - - /** - * Add recipe for direct deliver - * @param to To - */ - public addDirectRecipe(to: IRemoteUser) { - const recipe = { - type: "Direct", - to, - } as IDirectRecipe; - - this.addRecipe(recipe); - } - - /** - * Add recipe - * @param recipe Recipe - */ - public addRecipe(recipe: IRecipe) { - this.recipes.push(recipe); - } - - /** - * Execute delivers - */ - public async execute() { - if (!Users.isLocalUser(this.actor)) return; - - const inboxes = new Set<string>(); - - /* - build inbox list - - Process follower recipes first to avoid duplication when processing - direct recipes later. - */ - if (this.recipes.some((r) => isFollowers(r))) { - // followers deliver - // TODO: SELECT DISTINCT ON ("followerSharedInbox") "followerSharedInbox" みたいな問い合わせにすればよりパフォーマンス向上できそう - // ただ、sharedInboxがnullなリモートユーザーも稀におり、その対応ができなさそう? - const followers = (await Followings.find({ - where: { - followeeId: this.actor.id, - followerHost: Not(IsNull()), - }, - select: { - followerSharedInbox: true, - followerInbox: true, - }, - })) as { - followerSharedInbox: string | null; - followerInbox: string; - }[]; - - for (const following of followers) { - const inbox = following.followerSharedInbox || following.followerInbox; - inboxes.add(inbox); - } - } - - this.recipes - .filter( - (recipe): recipe is IDirectRecipe => - // followers recipes have already been processed - isDirect(recipe) && - // check that shared inbox has not been added yet - !(recipe.to.sharedInbox && inboxes.has(recipe.to.sharedInbox)) && - // check that they actually have an inbox - recipe.to.inbox != null, - ) - .forEach((recipe) => inboxes.add(recipe.to.inbox!)); - - const instancesToSkip = await skippedInstances( - // get (unique) list of hosts - Array.from( - new Set(Array.from(inboxes).map((inbox) => new URL(inbox).host)), - ), - ); - - // deliver - for (const inbox of inboxes) { - // skip instances as indicated - if (instancesToSkip.includes(new URL(inbox).host)) continue; - - deliver(this.actor, this.activity, inbox); - } - } -} - -//#region Utilities -/** - * Deliver activity to followers - * @param activity Activity - * @param from Followee - */ -export async function deliverToFollowers( - actor: { id: ILocalUser["id"]; host: null }, - activity: any, -) { - const manager = new DeliverManager(actor, activity); - manager.addFollowersRecipe(); - await manager.execute(); -} - -/** - * Deliver activity to user - * @param activity Activity - * @param to Target user - */ -export async function deliverToUser( - actor: { id: ILocalUser["id"]; host: null }, - activity: any, - to: IRemoteUser, -) { - const manager = new DeliverManager(actor, activity); - manager.addDirectRecipe(to); - await manager.execute(); -} -//#endregion diff --git a/packages/backend/src/remote/activitypub/kernel/accept/follow.ts b/packages/backend/src/remote/activitypub/kernel/accept/follow.ts deleted file mode 100644 index e430bbf576..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/accept/follow.ts +++ /dev/null @@ -1,32 +0,0 @@ -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import accept from "@/services/following/requests/accept.js"; -import type { IFollow } from "../../type.js"; -import DbResolver from "../../db-resolver.js"; -import { relayAccepted } from "@/services/relay.js"; - -export default async ( - actor: CacheableRemoteUser, - activity: IFollow, -): Promise<string> => { - // ※ activityはこっちから投げたフォローリクエストなので、activity.actorは存在するローカルユーザーである必要がある - - const dbResolver = new DbResolver(); - const follower = await dbResolver.getUserFromApId(activity.actor); - - if (follower == null) { - return "skip: follower not found"; - } - - if (follower.host != null) { - return "skip: follower is not a local user"; - } - - // relay - const match = activity.id?.match(/follow-relay\/(\w+)/); - if (match) { - return await relayAccepted(match[1]); - } - - await accept(actor, follower); - return "ok"; -}; diff --git a/packages/backend/src/remote/activitypub/kernel/accept/index.ts b/packages/backend/src/remote/activitypub/kernel/accept/index.ts deleted file mode 100644 index 5c73760ff3..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/accept/index.ts +++ /dev/null @@ -1,28 +0,0 @@ -import Resolver from "../../resolver.js"; -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import acceptFollow from "./follow.js"; -import type { IAccept } from "../../type.js"; -import { isFollow, getApType } from "../../type.js"; -import { apLogger } from "../../logger.js"; - -const logger = apLogger; - -export default async ( - actor: CacheableRemoteUser, - activity: IAccept, -): Promise<string> => { - const uri = activity.id || activity; - - logger.info(`Accept: ${uri}`); - - const resolver = new Resolver(); - - const object = await resolver.resolve(activity.object).catch((e) => { - logger.error(`Resolution failed: ${e}`); - throw e; - }); - - if (isFollow(object)) return await acceptFollow(actor, object); - - return `skip: Unknown Accept type: ${getApType(object)}`; -}; diff --git a/packages/backend/src/remote/activitypub/kernel/add/index.ts b/packages/backend/src/remote/activitypub/kernel/add/index.ts deleted file mode 100644 index b3606e5d93..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/add/index.ts +++ /dev/null @@ -1,26 +0,0 @@ -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import type { IAdd } from "../../type.js"; -import { resolveNote } from "../../models/note.js"; -import { addPinned } from "@/services/i/pin.js"; - -export default async ( - actor: CacheableRemoteUser, - activity: IAdd, -): Promise<void> => { - if ("actor" in activity && actor.uri !== activity.actor) { - throw new Error("invalid actor"); - } - - if (activity.target == null) { - throw new Error("target is null"); - } - - if (activity.target === actor.featured) { - const note = await resolveNote(activity.object); - if (note == null) throw new Error("note not found"); - await addPinned(actor, note.id); - return; - } - - throw new Error(`unknown target: ${activity.target}`); -}; diff --git a/packages/backend/src/remote/activitypub/kernel/announce/index.ts b/packages/backend/src/remote/activitypub/kernel/announce/index.ts deleted file mode 100644 index 975e070f92..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/announce/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -import Resolver from "../../resolver.js"; -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import announceNote from "./note.js"; -import type { IAnnounce } from "../../type.js"; -import { getApId } from "../../type.js"; -import { apLogger } from "../../logger.js"; - -const logger = apLogger; - -export default async ( - actor: CacheableRemoteUser, - activity: IAnnounce, -): Promise<void> => { - const uri = getApId(activity); - - logger.info(`Announce: ${uri}`); - - const resolver = new Resolver(); - - const targetUri = getApId(activity.object); - - announceNote(resolver, actor, activity, targetUri); -}; diff --git a/packages/backend/src/remote/activitypub/kernel/announce/note.ts b/packages/backend/src/remote/activitypub/kernel/announce/note.ts deleted file mode 100644 index 6cdaa61662..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/announce/note.ts +++ /dev/null @@ -1,84 +0,0 @@ -import type Resolver from "../../resolver.js"; -import post from "@/services/note/create.js"; -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import type { IAnnounce } from "../../type.js"; -import { getApId } from "../../type.js"; -import { fetchNote, resolveNote } from "../../models/note.js"; -import { apLogger } from "../../logger.js"; -import { extractDbHost } from "@/misc/convert-host.js"; -import { getApLock } from "@/misc/app-lock.js"; -import { parseAudience } from "../../audience.js"; -import { StatusError } from "@/misc/fetch.js"; -import { Notes } from "@/models/index.js"; -import { shouldBlockInstance } from "@/misc/should-block-instance.js"; - -const logger = apLogger; - -/** - * Handle announcement activities - */ -export default async function ( - resolver: Resolver, - actor: CacheableRemoteUser, - activity: IAnnounce, - targetUri: string, -): Promise<void> { - const uri = getApId(activity); - - if (actor.isSuspended) { - return; - } - - // Interrupt if you block the announcement destination - if (await shouldBlockInstance(extractDbHost(uri))) return; - - const unlock = await getApLock(uri); - - try { - // Check if something with the same URI is already registered - const exist = await fetchNote(uri); - if (exist) { - return; - } - - // Resolve Announce target - let renote; - try { - renote = await resolveNote(targetUri); - } catch (e) { - // Skip if target is 4xx - if (e instanceof StatusError) { - if (e.isClientError) { - logger.warn(`Ignored announce target ${targetUri} - ${e.statusCode}`); - return; - } - - logger.warn( - `Error in announce target ${targetUri} - ${e.statusCode || e}`, - ); - } - throw e; - } - - if (!(await Notes.isVisibleForMe(renote, actor.id))) - return "skip: invalid actor for this activity"; - - logger.info(`Creating the (Re)Note: ${uri}`); - - const activityAudience = await parseAudience( - actor, - activity.to, - activity.cc, - ); - - await post(actor, { - createdAt: activity.published ? new Date(activity.published) : null, - renote, - visibility: activityAudience.visibility, - visibleUsers: activityAudience.visibleUsers, - uri, - }); - } finally { - unlock(); - } -} diff --git a/packages/backend/src/remote/activitypub/kernel/block/index.ts b/packages/backend/src/remote/activitypub/kernel/block/index.ts deleted file mode 100644 index 4dc868ba10..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/block/index.ts +++ /dev/null @@ -1,29 +0,0 @@ -import type { IBlock } from "../../type.js"; -import block from "@/services/blocking/create.js"; -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import DbResolver from "../../db-resolver.js"; -import { Users } from "@/models/index.js"; - -export default async ( - actor: CacheableRemoteUser, - activity: IBlock, -): Promise<string> => { - // ※ There is a block target in activity.object, which should be a local user that exists. - - const dbResolver = new DbResolver(); - const blockee = await dbResolver.getUserFromApId(activity.object); - - if (blockee == null) { - return "skip: blockee not found"; - } - - if (blockee.host != null) { - return "skip: The user you are trying to block is not a local user"; - } - - await block( - await Users.findOneByOrFail({ id: actor.id }), - await Users.findOneByOrFail({ id: blockee.id }), - ); - return "ok"; -}; diff --git a/packages/backend/src/remote/activitypub/kernel/create/index.ts b/packages/backend/src/remote/activitypub/kernel/create/index.ts deleted file mode 100644 index 3dcf648247..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/create/index.ts +++ /dev/null @@ -1,51 +0,0 @@ -import Resolver from "../../resolver.js"; -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import createNote from "./note.js"; -import type { ICreate } from "../../type.js"; -import { getApId, isPost, getApType } from "../../type.js"; -import { apLogger } from "../../logger.js"; -import { toArray, concat, unique } from "@/prelude/array.js"; - -const logger = apLogger; - -export default async ( - actor: CacheableRemoteUser, - activity: ICreate, -): Promise<void> => { - const uri = getApId(activity); - - logger.info(`Create: ${uri}`); - - // copy audiences between activity <=> object. - if (typeof activity.object === "object") { - const to = unique( - concat([toArray(activity.to), toArray(activity.object.to)]), - ); - const cc = unique( - concat([toArray(activity.cc), toArray(activity.object.cc)]), - ); - - activity.to = to; - activity.cc = cc; - activity.object.to = to; - activity.object.cc = cc; - } - - // If there is no attributedTo, use Activity actor. - if (typeof activity.object === "object" && !activity.object.attributedTo) { - activity.object.attributedTo = activity.actor; - } - - const resolver = new Resolver(); - - const object = await resolver.resolve(activity.object).catch((e) => { - logger.error(`Resolution failed: ${e}`); - throw e; - }); - - if (isPost(object)) { - createNote(resolver, actor, object, false, activity); - } else { - logger.warn(`Unknown type: ${getApType(object)}`); - } -}; diff --git a/packages/backend/src/remote/activitypub/kernel/create/note.ts b/packages/backend/src/remote/activitypub/kernel/create/note.ts deleted file mode 100644 index 09c492730c..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/create/note.ts +++ /dev/null @@ -1,51 +0,0 @@ -import type Resolver from "../../resolver.js"; -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import { createNote, fetchNote } from "../../models/note.js"; -import type { IObject, ICreate } from "../../type.js"; -import { getApId } from "../../type.js"; -import { getApLock } from "@/misc/app-lock.js"; -import { extractDbHost } from "@/misc/convert-host.js"; -import { StatusError } from "@/misc/fetch.js"; - -/** - * Handle post creation activity - */ -export default async function ( - resolver: Resolver, - actor: CacheableRemoteUser, - note: IObject, - silent = false, - activity?: ICreate, -): Promise<string> { - const uri = getApId(note); - - if (typeof note === "object") { - if (actor.uri !== note.attributedTo) { - return "skip: actor.uri !== note.attributedTo"; - } - - if (typeof note.id === "string") { - if (extractDbHost(actor.uri) !== extractDbHost(note.id)) { - return "skip: host in actor.uri !== note.id"; - } - } - } - - const unlock = await getApLock(uri); - - try { - const exist = await fetchNote(note); - if (exist) return "skip: note exists"; - - await createNote(note, resolver, silent); - return "ok"; - } catch (e) { - if (e instanceof StatusError && e.isClientError) { - return `skip ${e.statusCode}`; - } else { - throw e; - } - } finally { - unlock(); - } -} diff --git a/packages/backend/src/remote/activitypub/kernel/delete/actor.ts b/packages/backend/src/remote/activitypub/kernel/delete/actor.ts deleted file mode 100644 index 3571135aa5..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/delete/actor.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { apLogger } from "../../logger.js"; -import { createDeleteAccountJob } from "@/queue/index.js"; -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import { Users } from "@/models/index.js"; - -const logger = apLogger; - -export async function deleteActor( - actor: CacheableRemoteUser, - uri: string, -): Promise<string> { - logger.info(`Deleting the Actor: ${uri}`); - - if (actor.uri !== uri) { - return `skip: delete actor ${actor.uri} !== ${uri}`; - } - - const user = await Users.findOneByOrFail({ id: actor.id }); - if (user.isDeleted) { - logger.info("skip: already deleted"); - } - - const job = await createDeleteAccountJob(actor); - - await Users.update(actor.id, { - isDeleted: true, - }); - - return `ok: queued ${job.name} ${job.id}`; -} diff --git a/packages/backend/src/remote/activitypub/kernel/delete/index.ts b/packages/backend/src/remote/activitypub/kernel/delete/index.ts deleted file mode 100644 index f9ad52de54..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/delete/index.ts +++ /dev/null @@ -1,55 +0,0 @@ -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import { toSingle } from "@/prelude/array.js"; -import { getApId, isTombstone, validPost, validActor } from "../../type.js"; -import deleteNote from "./note.js"; -import { deleteActor } from "./actor.js"; -import type { IDelete, IObject } from "../../type.js"; - -/** - * Handle delete activity - */ -export default async ( - actor: CacheableRemoteUser, - activity: IDelete, -): Promise<string> => { - if ("actor" in activity && actor.uri !== activity.actor) { - throw new Error("invalid actor"); - } - - // Type of object to be deleted - let formerType: string | undefined; - - if (typeof activity.object === "string") { - // The type is unknown, but it has disappeared - // anyway, so it does not remote resolve - formerType = undefined; - } else { - const object = activity.object as IObject; - if (isTombstone(object)) { - formerType = toSingle(object.formerType); - } else { - formerType = toSingle(object.type); - } - } - - const uri = getApId(activity.object); - - // Even if type is unknown, if actor and object are the same, - // it must be `Person`. - if (!formerType && actor.uri === uri) { - formerType = "Person"; - } - - // If not, fallback to `Note`. - if (!formerType) { - formerType = "Note"; - } - - if (validPost.includes(formerType)) { - return await deleteNote(actor, uri); - } else if (validActor.includes(formerType)) { - return await deleteActor(actor, uri); - } else { - return `Unknown type ${formerType}`; - } -}; diff --git a/packages/backend/src/remote/activitypub/kernel/delete/note.ts b/packages/backend/src/remote/activitypub/kernel/delete/note.ts deleted file mode 100644 index 69298e9175..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/delete/note.ts +++ /dev/null @@ -1,44 +0,0 @@ -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import deleteNode from "@/services/note/delete.js"; -import { apLogger } from "../../logger.js"; -import DbResolver from "../../db-resolver.js"; -import { getApLock } from "@/misc/app-lock.js"; -import { deleteMessage } from "@/services/messages/delete.js"; - -const logger = apLogger; - -export default async function ( - actor: CacheableRemoteUser, - uri: string, -): Promise<string> { - logger.info(`Deleting the Note: ${uri}`); - - const unlock = await getApLock(uri); - - try { - const dbResolver = new DbResolver(); - const note = await dbResolver.getNoteFromApId(uri); - - if (note == null) { - const message = await dbResolver.getMessageFromApId(uri); - if (message == null) return "message not found"; - - if (message.userId !== actor.id) { - return "The user trying to delete the post is not the post author"; - } - - await deleteMessage(message); - - return "ok: message deleted"; - } - - if (note.userId !== actor.id) { - return "The user trying to delete the post is not the post author"; - } - - await deleteNode(actor, note); - return "ok: note deleted"; - } finally { - unlock(); - } -} diff --git a/packages/backend/src/remote/activitypub/kernel/flag/index.ts b/packages/backend/src/remote/activitypub/kernel/flag/index.ts deleted file mode 100644 index 39ba8b3f4f..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/flag/index.ts +++ /dev/null @@ -1,37 +0,0 @@ -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import config from "@/config/index.js"; -import type { IFlag } from "../../type.js"; -import { getApIds } from "../../type.js"; -import { AbuseUserReports, Users } from "@/models/index.js"; -import { In } from "typeorm"; -import { genId } from "@/misc/gen-id.js"; - -export default async ( - actor: CacheableRemoteUser, - activity: IFlag, -): Promise<string> => { - // The object is `(User | Note) | (User | Note) []`, but it cannot be - // matched with all patterns of the DB schema, so the target user is the first - // user and it is stored as a comment. - const uris = getApIds(activity.object); - - const userIds = uris - .filter((uri) => uri.startsWith(`${config.url}/users/`)) - .map((uri) => uri.split("/").pop()!); - const users = await Users.findBy({ - id: In(userIds), - }); - if (users.length < 1) return "skip"; - - await AbuseUserReports.insert({ - id: genId(), - createdAt: new Date(), - targetUserId: users[0].id, - targetUserHost: users[0].host, - reporterId: actor.id, - reporterHost: actor.host, - comment: `${activity.content}\n${JSON.stringify(uris, null, 2)}`, - }); - - return "ok"; -}; diff --git a/packages/backend/src/remote/activitypub/kernel/follow.ts b/packages/backend/src/remote/activitypub/kernel/follow.ts deleted file mode 100644 index 1c1ef36cfa..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/follow.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import follow from "@/services/following/create.js"; -import type { IFollow } from "../type.js"; -import DbResolver from "../db-resolver.js"; - -export default async ( - actor: CacheableRemoteUser, - activity: IFollow, -): Promise<string> => { - const dbResolver = new DbResolver(); - const followee = await dbResolver.getUserFromApId(activity.object); - - if (followee == null) { - return "skip: followee not found"; - } - - if (followee.host != null) { - return "skip: user you are trying to follow is not a local user"; - } - - await follow(actor, followee, activity.id); - return "ok"; -}; diff --git a/packages/backend/src/remote/activitypub/kernel/index.ts b/packages/backend/src/remote/activitypub/kernel/index.ts deleted file mode 100644 index 58e354a512..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/index.ts +++ /dev/null @@ -1,111 +0,0 @@ -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import { toArray } from "@/prelude/array.js"; -import { - isCreate, - isDelete, - isUpdate, - isRead, - isFollow, - isAccept, - isReject, - isAdd, - isRemove, - isAnnounce, - isLike, - isUndo, - isBlock, - isCollectionOrOrderedCollection, - isCollection, - isFlag, - isMove, - getApId, -} from "../type.js"; -import { apLogger } from "../logger.js"; -import Resolver from "../resolver.js"; -import create from "./create/index.js"; -import performDeleteActivity from "./delete/index.js"; -import performUpdateActivity from "./update/index.js"; -import { performReadActivity } from "./read.js"; -import follow from "./follow.js"; -import undo from "./undo/index.js"; -import like from "./like.js"; -import announce from "./announce/index.js"; -import accept from "./accept/index.js"; -import reject from "./reject/index.js"; -import add from "./add/index.js"; -import remove from "./remove/index.js"; -import block from "./block/index.js"; -import flag from "./flag/index.js"; -import move from "./move/index.js"; -import type { IObject } from "../type.js"; -import { extractDbHost } from "@/misc/convert-host.js"; -import { shouldBlockInstance } from "@/misc/should-block-instance.js"; - -export async function performActivity( - actor: CacheableRemoteUser, - activity: IObject, -) { - if (isCollectionOrOrderedCollection(activity)) { - const resolver = new Resolver(); - for (const item of toArray( - isCollection(activity) ? activity.items : activity.orderedItems, - )) { - const act = await resolver.resolve(item); - try { - await performOneActivity(actor, act); - } catch (err) { - if (err instanceof Error || typeof err === "string") { - apLogger.error(err); - } - } - } - } else { - await performOneActivity(actor, activity); - } -} - -async function performOneActivity( - actor: CacheableRemoteUser, - activity: IObject, -): Promise<void> { - if (actor.isSuspended) return; - - if (typeof activity.id !== "undefined") { - const host = extractDbHost(getApId(activity)); - if (await shouldBlockInstance(host)) return; - } - - if (isCreate(activity)) { - await create(actor, activity); - } else if (isDelete(activity)) { - await performDeleteActivity(actor, activity); - } else if (isUpdate(activity)) { - await performUpdateActivity(actor, activity); - } else if (isRead(activity)) { - await performReadActivity(actor, activity); - } else if (isFollow(activity)) { - await follow(actor, activity); - } else if (isAccept(activity)) { - await accept(actor, activity); - } else if (isReject(activity)) { - await reject(actor, activity); - } else if (isAdd(activity)) { - await add(actor, activity).catch((err) => apLogger.error(err)); - } else if (isRemove(activity)) { - await remove(actor, activity).catch((err) => apLogger.error(err)); - } else if (isAnnounce(activity)) { - await announce(actor, activity); - } else if (isLike(activity)) { - await like(actor, activity); - } else if (isUndo(activity)) { - await undo(actor, activity); - } else if (isBlock(activity)) { - await block(actor, activity); - } else if (isFlag(activity)) { - await flag(actor, activity); - } else if (isMove(activity)) { - await move(actor, activity); - } else { - apLogger.warn(`unrecognized activity type: ${(activity as any).type}`); - } -} diff --git a/packages/backend/src/remote/activitypub/kernel/like.ts b/packages/backend/src/remote/activitypub/kernel/like.ts deleted file mode 100644 index 7b30d1cd54..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/like.ts +++ /dev/null @@ -1,28 +0,0 @@ -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import type { ILike } from "../type.js"; -import { getApId } from "../type.js"; -import create from "@/services/note/reaction/create.js"; -import { fetchNote, extractEmojis } from "../models/note.js"; - -export default async (actor: CacheableRemoteUser, activity: ILike) => { - const targetUri = getApId(activity.object); - - const note = await fetchNote(targetUri); - if (!note) return `skip: target note not found ${targetUri}`; - - await extractEmojis(activity.tag || [], actor.host).catch(() => null); - - return await create( - actor, - note, - activity._misskey_reaction || activity.content || activity.name, - ) - .catch((e) => { - if (e.id === "51c42bb4-931a-456b-bff7-e5a8a70dd298") { - return "skip: already reacted"; - } else { - throw e; - } - }) - .then(() => "ok"); -}; diff --git a/packages/backend/src/remote/activitypub/kernel/move/index.ts b/packages/backend/src/remote/activitypub/kernel/move/index.ts deleted file mode 100644 index 800fd7bfea..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/move/index.ts +++ /dev/null @@ -1,69 +0,0 @@ -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import { Followings, Users } from "@/models/index.js"; -import { - resolvePerson, - updatePerson, -} from "@/remote/activitypub/models/person.js"; -import create from "@/services/following/create.js"; -import deleteFollowing from "@/services/following/delete.js"; - -import type { IMove } from "../../type.js"; -import { getApHrefNullable } from "../../type.js"; - -export default async ( - actor: CacheableRemoteUser, - activity: IMove, -): Promise<string> => { - // ※ There is a block target in activity.object, which should be a local user that exists. - - // fetch the new and old accounts - const targetUri = getApHrefNullable(activity.target); - if (!targetUri) return "move: target uri is null"; - let new_acc = await resolvePerson(targetUri); - if (!actor.uri) return "move: actor uri is null"; - let old_acc = await resolvePerson(actor.uri); - - // update them if they're remote - if (new_acc.uri) await updatePerson(new_acc.uri); - if (old_acc.uri) await updatePerson(old_acc.uri); - - // retrieve updated users - new_acc = await resolvePerson(targetUri); - old_acc = await resolvePerson(actor.uri); - - // check if alsoKnownAs of the new account is valid - let isValidMove = true; - if (old_acc.uri) { - if (!new_acc.alsoKnownAs?.includes(old_acc.uri)) { - isValidMove = false; - } - } else if (!new_acc.alsoKnownAs?.includes(old_acc.id)) { - isValidMove = false; - } - if (!isValidMove) { - return "skip: accounts invalid"; - } - - // add target uri to movedToUri in order to indicate that the user has moved - await Users.update(old_acc.id, { movedToUri: targetUri }); - - // follow the new account and unfollow the old one - const followings = await Followings.findBy({ - followeeId: old_acc.id, - }); - followings.forEach(async (following) => { - // If follower is local - if (!following.followerHost) { - try { - const follower = await Users.findOneBy({ id: following.followerId }); - if (!follower) return; - await create(follower, new_acc); - await deleteFollowing(follower, old_acc); - } catch { - /* empty */ - } - } - }); - - return "ok"; -}; diff --git a/packages/backend/src/remote/activitypub/kernel/read.ts b/packages/backend/src/remote/activitypub/kernel/read.ts deleted file mode 100644 index 7cc70976c3..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/read.ts +++ /dev/null @@ -1,33 +0,0 @@ -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import type { IRead } from "../type.js"; -import { getApId } from "../type.js"; -import { isSelfHost, extractDbHost } from "@/misc/convert-host.js"; -import { MessagingMessages } from "@/models/index.js"; -import { readUserMessagingMessage } from "../../../server/api/common/read-messaging-message.js"; - -export const performReadActivity = async ( - actor: CacheableRemoteUser, - activity: IRead, -): Promise<string> => { - const id = await getApId(activity.object); - - if (!isSelfHost(extractDbHost(id))) { - return `skip: Read to foreign host (${id})`; - } - - const messageId = id.split("/").pop(); - - const message = await MessagingMessages.findOneBy({ id: messageId }); - if (message == null) { - return "skip: message not found"; - } - - if (actor.id !== message.recipientId) { - return "skip: actor is not a message recipient"; - } - - await readUserMessagingMessage(message.recipientId!, message.userId, [ - message.id, - ]); - return `ok: mark as read (${message.userId} => ${message.recipientId} ${message.id})`; -}; diff --git a/packages/backend/src/remote/activitypub/kernel/reject/follow.ts b/packages/backend/src/remote/activitypub/kernel/reject/follow.ts deleted file mode 100644 index 670c1556fd..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/reject/follow.ts +++ /dev/null @@ -1,33 +0,0 @@ -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import { remoteReject } from "@/services/following/reject.js"; -import type { IFollow } from "../../type.js"; -import DbResolver from "../../db-resolver.js"; -import { relayRejected } from "@/services/relay.js"; -import { Users } from "@/models/index.js"; - -export default async ( - actor: CacheableRemoteUser, - activity: IFollow, -): Promise<string> => { - // ※ `activity.actor` must be an existing local user, since `activity` is a follow request thrown from us. - - const dbResolver = new DbResolver(); - const follower = await dbResolver.getUserFromApId(activity.actor); - - if (follower == null) { - return "skip: follower not found"; - } - - if (!Users.isLocalUser(follower)) { - return "skip: follower is not a local user"; - } - - // relay - const match = activity.id?.match(/follow-relay\/(\w+)/); - if (match) { - return await relayRejected(match[1]); - } - - await remoteReject(actor, follower); - return "ok"; -}; diff --git a/packages/backend/src/remote/activitypub/kernel/reject/index.ts b/packages/backend/src/remote/activitypub/kernel/reject/index.ts deleted file mode 100644 index 10edb0f7a2..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/reject/index.ts +++ /dev/null @@ -1,28 +0,0 @@ -import Resolver from "../../resolver.js"; -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import rejectFollow from "./follow.js"; -import type { IReject } from "../../type.js"; -import { isFollow, getApType } from "../../type.js"; -import { apLogger } from "../../logger.js"; - -const logger = apLogger; - -export default async ( - actor: CacheableRemoteUser, - activity: IReject, -): Promise<string> => { - const uri = activity.id || activity; - - logger.info(`Reject: ${uri}`); - - const resolver = new Resolver(); - - const object = await resolver.resolve(activity.object).catch((e) => { - logger.error(`Resolution failed: ${e}`); - throw e; - }); - - if (isFollow(object)) return await rejectFollow(actor, object); - - return `skip: Unknown Reject type: ${getApType(object)}`; -}; diff --git a/packages/backend/src/remote/activitypub/kernel/remove/index.ts b/packages/backend/src/remote/activitypub/kernel/remove/index.ts deleted file mode 100644 index 0b4be6b5f2..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/remove/index.ts +++ /dev/null @@ -1,26 +0,0 @@ -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import type { IRemove } from "../../type.js"; -import { resolveNote } from "../../models/note.js"; -import { removePinned } from "@/services/i/pin.js"; - -export default async ( - actor: CacheableRemoteUser, - activity: IRemove, -): Promise<void> => { - if ("actor" in activity && actor.uri !== activity.actor) { - throw new Error("invalid actor"); - } - - if (activity.target == null) { - throw new Error("target is null"); - } - - if (activity.target === actor.featured) { - const note = await resolveNote(activity.object); - if (note == null) throw new Error("note not found"); - await removePinned(actor, note.id); - return; - } - - throw new Error(`unknown target: ${activity.target}`); -}; diff --git a/packages/backend/src/remote/activitypub/kernel/undo/accept.ts b/packages/backend/src/remote/activitypub/kernel/undo/accept.ts deleted file mode 100644 index 2cd05a77d2..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/undo/accept.ts +++ /dev/null @@ -1,30 +0,0 @@ -import unfollow from "@/services/following/delete.js"; -import cancelRequest from "@/services/following/requests/cancel.js"; -import type { IAccept } from "../../type.js"; -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import { Followings } from "@/models/index.js"; -import DbResolver from "../../db-resolver.js"; - -export default async ( - actor: CacheableRemoteUser, - activity: IAccept, -): Promise<string> => { - const dbResolver = new DbResolver(); - - const follower = await dbResolver.getUserFromApId(activity.object); - if (follower == null) { - return "skip: follower not found"; - } - - const following = await Followings.findOneBy({ - followerId: follower.id, - followeeId: actor.id, - }); - - if (following) { - await unfollow(follower, actor); - return "ok: unfollowed"; - } - - return "skip: skip: not followed"; -}; diff --git a/packages/backend/src/remote/activitypub/kernel/undo/announce.ts b/packages/backend/src/remote/activitypub/kernel/undo/announce.ts deleted file mode 100644 index a6e9c88c61..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/undo/announce.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Notes } from "@/models/index.js"; -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import type { IAnnounce } from "../../type.js"; -import { getApId } from "../../type.js"; -import deleteNote from "@/services/note/delete.js"; - -export const undoAnnounce = async ( - actor: CacheableRemoteUser, - activity: IAnnounce, -): Promise<string> => { - const uri = getApId(activity); - - const note = await Notes.findOneBy({ - uri, - userId: actor.id, - }); - - if (!note) return "skip: no such Announce"; - - await deleteNote(actor, note); - return "ok: deleted"; -}; diff --git a/packages/backend/src/remote/activitypub/kernel/undo/block.ts b/packages/backend/src/remote/activitypub/kernel/undo/block.ts deleted file mode 100644 index b4e1d8ee43..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/undo/block.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { IBlock } from "../../type.js"; -import unblock from "@/services/blocking/delete.js"; -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import DbResolver from "../../db-resolver.js"; -import { Users } from "@/models/index.js"; - -export default async ( - actor: CacheableRemoteUser, - activity: IBlock, -): Promise<string> => { - const dbResolver = new DbResolver(); - const blockee = await dbResolver.getUserFromApId(activity.object); - - if (blockee == null) { - return "skip: blockee not found"; - } - - if (blockee.host != null) { - return "skip: The user you are trying to unblock is not a local user"; - } - - await unblock(await Users.findOneByOrFail({ id: actor.id }), blockee); - return "ok"; -}; diff --git a/packages/backend/src/remote/activitypub/kernel/undo/follow.ts b/packages/backend/src/remote/activitypub/kernel/undo/follow.ts deleted file mode 100644 index 1c4648cf90..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/undo/follow.ts +++ /dev/null @@ -1,44 +0,0 @@ -import unfollow from "@/services/following/delete.js"; -import cancelRequest from "@/services/following/requests/cancel.js"; -import type { IFollow } from "../../type.js"; -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import { FollowRequests, Followings } from "@/models/index.js"; -import DbResolver from "../../db-resolver.js"; - -export default async ( - actor: CacheableRemoteUser, - activity: IFollow, -): Promise<string> => { - const dbResolver = new DbResolver(); - - const followee = await dbResolver.getUserFromApId(activity.object); - if (followee == null) { - return "skip: followee not found"; - } - - if (followee.host != null) { - return "skip: The user you are trying to unfollow is not a local user"; - } - - const req = await FollowRequests.findOneBy({ - followerId: actor.id, - followeeId: followee.id, - }); - - const following = await Followings.findOneBy({ - followerId: actor.id, - followeeId: followee.id, - }); - - if (req) { - await cancelRequest(followee, actor); - return "ok: follow request canceled"; - } - - if (following) { - await unfollow(actor, followee); - return "ok: unfollowed"; - } - - return "skip: Not requested or followed"; -}; diff --git a/packages/backend/src/remote/activitypub/kernel/undo/index.ts b/packages/backend/src/remote/activitypub/kernel/undo/index.ts deleted file mode 100644 index f0e2316fab..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/undo/index.ts +++ /dev/null @@ -1,47 +0,0 @@ -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import type { IUndo } from "../../type.js"; -import { - isFollow, - isBlock, - isLike, - isAnnounce, - getApType, - isAccept, -} from "../../type.js"; -import unfollow from "./follow.js"; -import unblock from "./block.js"; -import undoLike from "./like.js"; -import undoAccept from "./accept.js"; -import { undoAnnounce } from "./announce.js"; -import Resolver from "../../resolver.js"; -import { apLogger } from "../../logger.js"; - -const logger = apLogger; - -export default async ( - actor: CacheableRemoteUser, - activity: IUndo, -): Promise<string> => { - if ("actor" in activity && actor.uri !== activity.actor) { - throw new Error("invalid actor"); - } - - const uri = activity.id || activity; - - logger.info(`Undo: ${uri}`); - - const resolver = new Resolver(); - - const object = await resolver.resolve(activity.object).catch((e) => { - logger.error(`Resolution failed: ${e}`); - throw e; - }); - - if (isFollow(object)) return await unfollow(actor, object); - if (isBlock(object)) return await unblock(actor, object); - if (isLike(object)) return await undoLike(actor, object); - if (isAnnounce(object)) return await undoAnnounce(actor, object); - if (isAccept(object)) return await undoAccept(actor, object); - - return `skip: unknown object type ${getApType(object)}`; -}; diff --git a/packages/backend/src/remote/activitypub/kernel/undo/like.ts b/packages/backend/src/remote/activitypub/kernel/undo/like.ts deleted file mode 100644 index 90220e203d..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/undo/like.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import type { ILike } from "../../type.js"; -import { getApId } from "../../type.js"; -import deleteReaction from "@/services/note/reaction/delete.js"; -import { fetchNote } from "../../models/note.js"; - -/** - * Process Undo.Like activity - */ -export default async (actor: CacheableRemoteUser, activity: ILike) => { - const targetUri = getApId(activity.object); - - const note = await fetchNote(targetUri); - if (!note) return `skip: target note not found ${targetUri}`; - - await deleteReaction(actor, note).catch((e) => { - if (e.id === "60527ec9-b4cb-4a88-a6bd-32d3ad26817d") return; - throw e; - }); - - return "ok"; -}; diff --git a/packages/backend/src/remote/activitypub/kernel/update/index.ts b/packages/backend/src/remote/activitypub/kernel/update/index.ts deleted file mode 100644 index 4f1514ddd1..0000000000 --- a/packages/backend/src/remote/activitypub/kernel/update/index.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import type { IUpdate } from "../../type.js"; -import { getApType, isActor } from "../../type.js"; -import { apLogger } from "../../logger.js"; -import { updateQuestion } from "../../models/question.js"; -import Resolver from "../../resolver.js"; -import { updatePerson } from "../../models/person.js"; - -/** - * Handler for the Update activity - */ -export default async ( - actor: CacheableRemoteUser, - activity: IUpdate, -): Promise<string> => { - if ("actor" in activity && actor.uri !== activity.actor) { - return "skip: invalid actor"; - } - - apLogger.debug("Update"); - - const resolver = new Resolver(); - - const object = await resolver.resolve(activity.object).catch((e) => { - apLogger.error(`Resolution failed: ${e}`); - throw e; - }); - - if (isActor(object)) { - await updatePerson(actor.uri!, resolver, object); - return "ok: Person updated"; - } else if (getApType(object) === "Question") { - await updateQuestion(object, resolver).catch((e) => console.log(e)); - return "ok: Question updated"; - } else { - return `skip: Unknown type: ${getApType(object)}`; - } -}; diff --git a/packages/backend/src/remote/activitypub/logger.ts b/packages/backend/src/remote/activitypub/logger.ts deleted file mode 100644 index 47383cf7fa..0000000000 --- a/packages/backend/src/remote/activitypub/logger.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { remoteLogger } from "../logger.js"; - -export const apLogger = remoteLogger.createSubLogger("ap", "magenta"); diff --git a/packages/backend/src/remote/activitypub/misc/contexts.ts b/packages/backend/src/remote/activitypub/misc/contexts.ts deleted file mode 100644 index 8c97b59729..0000000000 --- a/packages/backend/src/remote/activitypub/misc/contexts.ts +++ /dev/null @@ -1,525 +0,0 @@ -const id_v1 = { - "@context": { - id: "@id", - type: "@type", - - cred: "https://w3id.org/credentials#", - dc: "http://purl.org/dc/terms/", - identity: "https://w3id.org/identity#", - perm: "https://w3id.org/permissions#", - ps: "https://w3id.org/payswarm#", - rdf: "http://www.w3.org/1999/02/22-rdf-syntax-ns#", - rdfs: "http://www.w3.org/2000/01/rdf-schema#", - sec: "https://w3id.org/security#", - schema: "http://schema.org/", - xsd: "http://www.w3.org/2001/XMLSchema#", - - Group: "https://www.w3.org/ns/activitystreams#Group", - - claim: { "@id": "cred:claim", "@type": "@id" }, - credential: { "@id": "cred:credential", "@type": "@id" }, - issued: { "@id": "cred:issued", "@type": "xsd:dateTime" }, - issuer: { "@id": "cred:issuer", "@type": "@id" }, - recipient: { "@id": "cred:recipient", "@type": "@id" }, - Credential: "cred:Credential", - CryptographicKeyCredential: "cred:CryptographicKeyCredential", - - about: { "@id": "schema:about", "@type": "@id" }, - address: { "@id": "schema:address", "@type": "@id" }, - addressCountry: "schema:addressCountry", - addressLocality: "schema:addressLocality", - addressRegion: "schema:addressRegion", - comment: "rdfs:comment", - created: { "@id": "dc:created", "@type": "xsd:dateTime" }, - creator: { "@id": "dc:creator", "@type": "@id" }, - description: "schema:description", - email: "schema:email", - familyName: "schema:familyName", - givenName: "schema:givenName", - image: { "@id": "schema:image", "@type": "@id" }, - label: "rdfs:label", - name: "schema:name", - postalCode: "schema:postalCode", - streetAddress: "schema:streetAddress", - title: "dc:title", - url: { "@id": "schema:url", "@type": "@id" }, - Person: "schema:Person", - PostalAddress: "schema:PostalAddress", - Organization: "schema:Organization", - - identityService: { "@id": "identity:identityService", "@type": "@id" }, - idp: { "@id": "identity:idp", "@type": "@id" }, - Identity: "identity:Identity", - - paymentProcessor: "ps:processor", - preferences: { "@id": "ps:preferences", "@type": "@vocab" }, - - cipherAlgorithm: "sec:cipherAlgorithm", - cipherData: "sec:cipherData", - cipherKey: "sec:cipherKey", - digestAlgorithm: "sec:digestAlgorithm", - digestValue: "sec:digestValue", - domain: "sec:domain", - expires: { "@id": "sec:expiration", "@type": "xsd:dateTime" }, - initializationVector: "sec:initializationVector", - member: { "@id": "schema:member", "@type": "@id" }, - memberOf: { "@id": "schema:memberOf", "@type": "@id" }, - nonce: "sec:nonce", - normalizationAlgorithm: "sec:normalizationAlgorithm", - owner: { "@id": "sec:owner", "@type": "@id" }, - password: "sec:password", - privateKey: { "@id": "sec:privateKey", "@type": "@id" }, - privateKeyPem: "sec:privateKeyPem", - publicKey: { "@id": "sec:publicKey", "@type": "@id" }, - publicKeyPem: "sec:publicKeyPem", - publicKeyService: { "@id": "sec:publicKeyService", "@type": "@id" }, - revoked: { "@id": "sec:revoked", "@type": "xsd:dateTime" }, - signature: "sec:signature", - signatureAlgorithm: "sec:signatureAlgorithm", - signatureValue: "sec:signatureValue", - CryptographicKey: "sec:Key", - EncryptedMessage: "sec:EncryptedMessage", - GraphSignature2012: "sec:GraphSignature2012", - LinkedDataSignature2015: "sec:LinkedDataSignature2015", - - accessControl: { "@id": "perm:accessControl", "@type": "@id" }, - writePermission: { "@id": "perm:writePermission", "@type": "@id" }, - }, -}; - -const security_v1 = { - "@context": { - id: "@id", - type: "@type", - - dc: "http://purl.org/dc/terms/", - sec: "https://w3id.org/security#", - xsd: "http://www.w3.org/2001/XMLSchema#", - - EcdsaKoblitzSignature2016: "sec:EcdsaKoblitzSignature2016", - Ed25519Signature2018: "sec:Ed25519Signature2018", - EncryptedMessage: "sec:EncryptedMessage", - GraphSignature2012: "sec:GraphSignature2012", - LinkedDataSignature2015: "sec:LinkedDataSignature2015", - LinkedDataSignature2016: "sec:LinkedDataSignature2016", - CryptographicKey: "sec:Key", - - authenticationTag: "sec:authenticationTag", - canonicalizationAlgorithm: "sec:canonicalizationAlgorithm", - cipherAlgorithm: "sec:cipherAlgorithm", - cipherData: "sec:cipherData", - cipherKey: "sec:cipherKey", - created: { "@id": "dc:created", "@type": "xsd:dateTime" }, - creator: { "@id": "dc:creator", "@type": "@id" }, - digestAlgorithm: "sec:digestAlgorithm", - digestValue: "sec:digestValue", - domain: "sec:domain", - encryptionKey: "sec:encryptionKey", - expiration: { "@id": "sec:expiration", "@type": "xsd:dateTime" }, - expires: { "@id": "sec:expiration", "@type": "xsd:dateTime" }, - initializationVector: "sec:initializationVector", - iterationCount: "sec:iterationCount", - nonce: "sec:nonce", - normalizationAlgorithm: "sec:normalizationAlgorithm", - owner: { "@id": "sec:owner", "@type": "@id" }, - password: "sec:password", - privateKey: { "@id": "sec:privateKey", "@type": "@id" }, - privateKeyPem: "sec:privateKeyPem", - publicKey: { "@id": "sec:publicKey", "@type": "@id" }, - publicKeyBase58: "sec:publicKeyBase58", - publicKeyPem: "sec:publicKeyPem", - publicKeyWif: "sec:publicKeyWif", - publicKeyService: { "@id": "sec:publicKeyService", "@type": "@id" }, - revoked: { "@id": "sec:revoked", "@type": "xsd:dateTime" }, - salt: "sec:salt", - signature: "sec:signature", - signatureAlgorithm: "sec:signingAlgorithm", - signatureValue: "sec:signatureValue", - }, -}; - -const activitystreams = { - "@context": { - "@vocab": "_:", - xsd: "http://www.w3.org/2001/XMLSchema#", - as: "https://www.w3.org/ns/activitystreams#", - ldp: "http://www.w3.org/ns/ldp#", - vcard: "http://www.w3.org/2006/vcard/ns#", - id: "@id", - type: "@type", - Accept: "as:Accept", - Activity: "as:Activity", - IntransitiveActivity: "as:IntransitiveActivity", - Add: "as:Add", - Announce: "as:Announce", - Application: "as:Application", - Arrive: "as:Arrive", - Article: "as:Article", - Audio: "as:Audio", - Block: "as:Block", - Collection: "as:Collection", - CollectionPage: "as:CollectionPage", - Relationship: "as:Relationship", - Create: "as:Create", - Delete: "as:Delete", - Dislike: "as:Dislike", - Document: "as:Document", - Event: "as:Event", - Follow: "as:Follow", - Flag: "as:Flag", - Group: "as:Group", - Ignore: "as:Ignore", - Image: "as:Image", - Invite: "as:Invite", - Join: "as:Join", - Leave: "as:Leave", - Like: "as:Like", - Link: "as:Link", - Mention: "as:Mention", - Note: "as:Note", - Object: "as:Object", - Offer: "as:Offer", - OrderedCollection: "as:OrderedCollection", - OrderedCollectionPage: "as:OrderedCollectionPage", - Organization: "as:Organization", - Page: "as:Page", - Person: "as:Person", - Place: "as:Place", - Profile: "as:Profile", - Question: "as:Question", - Reject: "as:Reject", - Remove: "as:Remove", - Service: "as:Service", - TentativeAccept: "as:TentativeAccept", - TentativeReject: "as:TentativeReject", - Tombstone: "as:Tombstone", - Undo: "as:Undo", - Update: "as:Update", - Video: "as:Video", - View: "as:View", - Listen: "as:Listen", - Read: "as:Read", - Move: "as:Move", - Travel: "as:Travel", - IsFollowing: "as:IsFollowing", - IsFollowedBy: "as:IsFollowedBy", - IsContact: "as:IsContact", - IsMember: "as:IsMember", - subject: { - "@id": "as:subject", - "@type": "@id", - }, - relationship: { - "@id": "as:relationship", - "@type": "@id", - }, - actor: { - "@id": "as:actor", - "@type": "@id", - }, - attributedTo: { - "@id": "as:attributedTo", - "@type": "@id", - }, - attachment: { - "@id": "as:attachment", - "@type": "@id", - }, - bcc: { - "@id": "as:bcc", - "@type": "@id", - }, - bto: { - "@id": "as:bto", - "@type": "@id", - }, - cc: { - "@id": "as:cc", - "@type": "@id", - }, - context: { - "@id": "as:context", - "@type": "@id", - }, - current: { - "@id": "as:current", - "@type": "@id", - }, - first: { - "@id": "as:first", - "@type": "@id", - }, - generator: { - "@id": "as:generator", - "@type": "@id", - }, - icon: { - "@id": "as:icon", - "@type": "@id", - }, - image: { - "@id": "as:image", - "@type": "@id", - }, - inReplyTo: { - "@id": "as:inReplyTo", - "@type": "@id", - }, - items: { - "@id": "as:items", - "@type": "@id", - }, - instrument: { - "@id": "as:instrument", - "@type": "@id", - }, - orderedItems: { - "@id": "as:items", - "@type": "@id", - "@container": "@list", - }, - last: { - "@id": "as:last", - "@type": "@id", - }, - location: { - "@id": "as:location", - "@type": "@id", - }, - next: { - "@id": "as:next", - "@type": "@id", - }, - object: { - "@id": "as:object", - "@type": "@id", - }, - oneOf: { - "@id": "as:oneOf", - "@type": "@id", - }, - anyOf: { - "@id": "as:anyOf", - "@type": "@id", - }, - closed: { - "@id": "as:closed", - "@type": "xsd:dateTime", - }, - origin: { - "@id": "as:origin", - "@type": "@id", - }, - accuracy: { - "@id": "as:accuracy", - "@type": "xsd:float", - }, - prev: { - "@id": "as:prev", - "@type": "@id", - }, - preview: { - "@id": "as:preview", - "@type": "@id", - }, - replies: { - "@id": "as:replies", - "@type": "@id", - }, - result: { - "@id": "as:result", - "@type": "@id", - }, - audience: { - "@id": "as:audience", - "@type": "@id", - }, - partOf: { - "@id": "as:partOf", - "@type": "@id", - }, - tag: { - "@id": "as:tag", - "@type": "@id", - }, - target: { - "@id": "as:target", - "@type": "@id", - }, - to: { - "@id": "as:to", - "@type": "@id", - }, - url: { - "@id": "as:url", - "@type": "@id", - }, - altitude: { - "@id": "as:altitude", - "@type": "xsd:float", - }, - content: "as:content", - contentMap: { - "@id": "as:content", - "@container": "@language", - }, - name: "as:name", - nameMap: { - "@id": "as:name", - "@container": "@language", - }, - duration: { - "@id": "as:duration", - "@type": "xsd:duration", - }, - endTime: { - "@id": "as:endTime", - "@type": "xsd:dateTime", - }, - height: { - "@id": "as:height", - "@type": "xsd:nonNegativeInteger", - }, - href: { - "@id": "as:href", - "@type": "@id", - }, - hreflang: "as:hreflang", - latitude: { - "@id": "as:latitude", - "@type": "xsd:float", - }, - longitude: { - "@id": "as:longitude", - "@type": "xsd:float", - }, - mediaType: "as:mediaType", - published: { - "@id": "as:published", - "@type": "xsd:dateTime", - }, - radius: { - "@id": "as:radius", - "@type": "xsd:float", - }, - rel: "as:rel", - startIndex: { - "@id": "as:startIndex", - "@type": "xsd:nonNegativeInteger", - }, - startTime: { - "@id": "as:startTime", - "@type": "xsd:dateTime", - }, - summary: "as:summary", - summaryMap: { - "@id": "as:summary", - "@container": "@language", - }, - totalItems: { - "@id": "as:totalItems", - "@type": "xsd:nonNegativeInteger", - }, - units: "as:units", - updated: { - "@id": "as:updated", - "@type": "xsd:dateTime", - }, - width: { - "@id": "as:width", - "@type": "xsd:nonNegativeInteger", - }, - describes: { - "@id": "as:describes", - "@type": "@id", - }, - formerType: { - "@id": "as:formerType", - "@type": "@id", - }, - deleted: { - "@id": "as:deleted", - "@type": "xsd:dateTime", - }, - inbox: { - "@id": "ldp:inbox", - "@type": "@id", - }, - outbox: { - "@id": "as:outbox", - "@type": "@id", - }, - following: { - "@id": "as:following", - "@type": "@id", - }, - followers: { - "@id": "as:followers", - "@type": "@id", - }, - streams: { - "@id": "as:streams", - "@type": "@id", - }, - preferredUsername: "as:preferredUsername", - endpoints: { - "@id": "as:endpoints", - "@type": "@id", - }, - uploadMedia: { - "@id": "as:uploadMedia", - "@type": "@id", - }, - proxyUrl: { - "@id": "as:proxyUrl", - "@type": "@id", - }, - liked: { - "@id": "as:liked", - "@type": "@id", - }, - oauthAuthorizationEndpoint: { - "@id": "as:oauthAuthorizationEndpoint", - "@type": "@id", - }, - oauthTokenEndpoint: { - "@id": "as:oauthTokenEndpoint", - "@type": "@id", - }, - provideClientKey: { - "@id": "as:provideClientKey", - "@type": "@id", - }, - signClientKey: { - "@id": "as:signClientKey", - "@type": "@id", - }, - sharedInbox: { - "@id": "as:sharedInbox", - "@type": "@id", - }, - Public: { - "@id": "as:Public", - "@type": "@id", - }, - source: "as:source", - likes: { - "@id": "as:likes", - "@type": "@id", - }, - shares: { - "@id": "as:shares", - "@type": "@id", - }, - alsoKnownAs: { - "@id": "as:alsoKnownAs", - "@type": "@id", - }, - }, -}; - -export const CONTEXTS: Record<string, unknown> = { - "https://w3id.org/identity/v1": id_v1, - "https://w3id.org/security/v1": security_v1, - "https://www.w3.org/ns/activitystreams": activitystreams, -}; diff --git a/packages/backend/src/remote/activitypub/misc/get-note-html.ts b/packages/backend/src/remote/activitypub/misc/get-note-html.ts deleted file mode 100644 index cb5294f731..0000000000 --- a/packages/backend/src/remote/activitypub/misc/get-note-html.ts +++ /dev/null @@ -1,8 +0,0 @@ -import * as mfm from "mfm-js"; -import type { Note } from "@/models/entities/note.js"; -import { toHtml } from "../../../mfm/to-html.js"; - -export default function (note: Note) { - if (!note.text) return ""; - return toHtml(mfm.parse(note.text), JSON.parse(note.mentionedRemoteUsers)); -} diff --git a/packages/backend/src/remote/activitypub/misc/html-to-mfm.ts b/packages/backend/src/remote/activitypub/misc/html-to-mfm.ts deleted file mode 100644 index 9d71a46a36..0000000000 --- a/packages/backend/src/remote/activitypub/misc/html-to-mfm.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { IObject } from "../type.js"; -import { extractApHashtagObjects } from "../models/tag.js"; -import { fromHtml } from "../../../mfm/from-html.js"; - -export function htmlToMfm(html: string, tag?: IObject | IObject[]) { - const hashtagNames = extractApHashtagObjects(tag) - .map((x) => x.name) - .filter((x): x is string => x != null); - - return fromHtml(html, hashtagNames); -} diff --git a/packages/backend/src/remote/activitypub/misc/ld-signature.ts b/packages/backend/src/remote/activitypub/misc/ld-signature.ts deleted file mode 100644 index 1657597ab6..0000000000 --- a/packages/backend/src/remote/activitypub/misc/ld-signature.ts +++ /dev/null @@ -1,143 +0,0 @@ -import * as crypto from "node:crypto"; -import jsonld from "jsonld"; -import { CONTEXTS } from "./contexts.js"; -import fetch from "node-fetch"; -import { httpAgent, httpsAgent } from "@/misc/fetch.js"; - -// RsaSignature2017 based from https://github.com/transmute-industries/RsaSignature2017 - -export class LdSignature { - public debug = false; - public preLoad = true; - public loderTimeout = 10 * 1000; - - constructor() {} - - public async signRsaSignature2017( - data: any, - privateKey: string, - creator: string, - domain?: string, - created?: Date, - ): Promise<any> { - const options = { - type: "RsaSignature2017", - creator, - domain, - nonce: crypto.randomBytes(16).toString("hex"), - created: (created || new Date()).toISOString(), - } as { - type: string; - creator: string; - domain?: string; - nonce: string; - created: string; - }; - - if (!domain) { - options.domain = undefined; - } - - const toBeSigned = await this.createVerifyData(data, options); - - const signer = crypto.createSign("sha256"); - signer.update(toBeSigned); - signer.end(); - - const signature = signer.sign(privateKey); - - return { - ...data, - signature: { - ...options, - signatureValue: signature.toString("base64"), - }, - }; - } - - public async verifyRsaSignature2017( - data: any, - publicKey: string, - ): Promise<boolean> { - const toBeSigned = await this.createVerifyData(data, data.signature); - const verifier = crypto.createVerify("sha256"); - verifier.update(toBeSigned); - return verifier.verify(publicKey, data.signature.signatureValue, "base64"); - } - - public async createVerifyData(data: any, options: any) { - const transformedOptions = { - ...options, - "@context": "https://w3id.org/identity/v1", - }; - delete transformedOptions["type"]; - delete transformedOptions["id"]; - delete transformedOptions["signatureValue"]; - const canonizedOptions = await this.normalize(transformedOptions); - const optionsHash = this.sha256(canonizedOptions); - const transformedData = { ...data }; - delete transformedData["signature"]; - const cannonidedData = await this.normalize(transformedData); - if (this.debug) console.debug(`cannonidedData: ${cannonidedData}`); - const documentHash = this.sha256(cannonidedData); - const verifyData = `${optionsHash}${documentHash}`; - return verifyData; - } - - public async normalize(data: any) { - const customLoader = this.getLoader(); - return await jsonld.normalize(data, { - documentLoader: customLoader, - }); - } - - private getLoader() { - return async (url: string): Promise<any> => { - if (!url.match("^https?://")) throw new Error(`Invalid URL ${url}`); - - if (this.preLoad) { - if (url in CONTEXTS) { - if (this.debug) console.debug(`HIT: ${url}`); - return { - contextUrl: null, - document: CONTEXTS[url], - documentUrl: url, - }; - } - } - - if (this.debug) console.debug(`MISS: ${url}`); - const document = await this.fetchDocument(url); - return { - contextUrl: null, - document: document, - documentUrl: url, - }; - }; - } - - private async fetchDocument(url: string) { - const json = await fetch(url, { - headers: { - Accept: "application/ld+json, application/json", - }, - // TODO - //timeout: this.loderTimeout, - agent: (u) => (u.protocol === "http:" ? httpAgent : httpsAgent), - }).then((res) => { - if (!res.ok) { - throw new Error(`${res.status} ${res.statusText}`); - } else { - return res.json(); - } - }); - - return json; - } - - public sha256(data: string): string { - const hash = crypto.createHash("sha256"); - hash.update(data); - return hash.digest("hex"); - } -} diff --git a/packages/backend/src/remote/activitypub/models/icon.ts b/packages/backend/src/remote/activitypub/models/icon.ts deleted file mode 100644 index 50794a937d..0000000000 --- a/packages/backend/src/remote/activitypub/models/icon.ts +++ /dev/null @@ -1,5 +0,0 @@ -export type IIcon = { - type: string; - mediaType?: string; - url?: string; -}; diff --git a/packages/backend/src/remote/activitypub/models/identifier.ts b/packages/backend/src/remote/activitypub/models/identifier.ts deleted file mode 100644 index f6c3bb8c88..0000000000 --- a/packages/backend/src/remote/activitypub/models/identifier.ts +++ /dev/null @@ -1,5 +0,0 @@ -export type IIdentifier = { - type: string; - name: string; - value: string; -}; diff --git a/packages/backend/src/remote/activitypub/models/image.ts b/packages/backend/src/remote/activitypub/models/image.ts deleted file mode 100644 index 211aa3931e..0000000000 --- a/packages/backend/src/remote/activitypub/models/image.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { uploadFromUrl } from "@/services/drive/upload-from-url.js"; -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import { IRemoteUser } from "@/models/entities/user.js"; -import Resolver from "../resolver.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { apLogger } from "../logger.js"; -import type { DriveFile } from "@/models/entities/drive-file.js"; -import { DriveFiles, Users } from "@/models/index.js"; -import { truncate } from "@/misc/truncate.js"; -import { DB_MAX_IMAGE_COMMENT_LENGTH } from "@/misc/hard-limits.js"; - -const logger = apLogger; - -/** - * create an Image. - */ -export async function createImage( - actor: CacheableRemoteUser, - value: any, -): Promise<DriveFile> { - // Skip if author is frozen. - if (actor.isSuspended) { - throw new Error("actor has been suspended"); - } - - const image = (await new Resolver().resolve(value)) as any; - - if (image.url == null) { - throw new Error("invalid image: url not privided"); - } - - if (!image.url.startsWith("https://") && !image.url.startsWith("http://")) { - throw new Error("invalid image: unexpected shcema of url: " + image.url); - } - - logger.info(`Creating the Image: ${image.url}`); - - const instance = await fetchMeta(); - - let file = await uploadFromUrl({ - url: image.url, - user: actor, - uri: image.url, - sensitive: image.sensitive, - isLink: !instance.cacheRemoteFiles, - comment: truncate(image.name, DB_MAX_IMAGE_COMMENT_LENGTH), - }); - - if (file.isLink) { - // If the URL is different, it means that the same image was previously - // registered with a different URL, so update the URL - if (file.url !== image.url) { - await DriveFiles.update( - { id: file.id }, - { - url: image.url, - uri: image.url, - }, - ); - - file = await DriveFiles.findOneByOrFail({ id: file.id }); - } - } - - return file; -} - -/** - * Resolve Image. - * - * If the target Image is registered in Calckey, return it, otherwise - * Fetch from remote server, register with Calckey and return it. - */ -export async function resolveImage( - actor: CacheableRemoteUser, - value: any, -): Promise<DriveFile> { - // TODO - - // Fetch from remote server and register - return await createImage(actor, value); -} diff --git a/packages/backend/src/remote/activitypub/models/mention.ts b/packages/backend/src/remote/activitypub/models/mention.ts deleted file mode 100644 index b888fa21a4..0000000000 --- a/packages/backend/src/remote/activitypub/models/mention.ts +++ /dev/null @@ -1,36 +0,0 @@ -import promiseLimit from "promise-limit"; -import { toArray, unique } from "@/prelude/array.js"; -import type { CacheableUser } from "@/models/entities/user.js"; -import { User } from "@/models/entities/user.js"; -import type { IObject, IApMention } from "../type.js"; -import { isMention } from "../type.js"; -import Resolver from "../resolver.js"; -import { resolvePerson } from "./person.js"; - -export async function extractApMentions( - tags: IObject | IObject[] | null | undefined, -) { - const hrefs = unique( - extractApMentionObjects(tags).map((x) => x.href as string), - ); - - const resolver = new Resolver(); - - const limit = promiseLimit<CacheableUser | null>(2); - const mentionedUsers = ( - await Promise.all( - hrefs.map((x) => - limit(() => resolvePerson(x, resolver).catch(() => null)), - ), - ) - ).filter((x): x is CacheableUser => x != null); - - return mentionedUsers; -} - -export function extractApMentionObjects( - tags: IObject | IObject[] | null | undefined, -): IApMention[] { - if (tags == null) return []; - return toArray(tags).filter(isMention); -} diff --git a/packages/backend/src/remote/activitypub/models/note.ts b/packages/backend/src/remote/activitypub/models/note.ts deleted file mode 100644 index 033157b081..0000000000 --- a/packages/backend/src/remote/activitypub/models/note.ts +++ /dev/null @@ -1,499 +0,0 @@ -import promiseLimit from "promise-limit"; - -import config from "@/config/index.js"; -import Resolver from "../resolver.js"; -import post from "@/services/note/create.js"; -import { resolvePerson } from "./person.js"; -import { resolveImage } from "./image.js"; -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import { htmlToMfm } from "../misc/html-to-mfm.js"; -import { extractApHashtags } from "./tag.js"; -import { unique, toArray, toSingle } from "@/prelude/array.js"; -import { extractPollFromQuestion } from "./question.js"; -import vote from "@/services/note/polls/vote.js"; -import { apLogger } from "../logger.js"; -import type { DriveFile } from "@/models/entities/drive-file.js"; -import { deliverQuestionUpdate } from "@/services/note/polls/update.js"; -import { extractDbHost, toPuny } from "@/misc/convert-host.js"; -import { Emojis, Polls, MessagingMessages } from "@/models/index.js"; -import type { Note } from "@/models/entities/note.js"; -import type { IObject, IPost } from "../type.js"; -import { - getOneApId, - getApId, - getOneApHrefNullable, - validPost, - isEmoji, - getApType, -} from "../type.js"; -import type { Emoji } from "@/models/entities/emoji.js"; -import { genId } from "@/misc/gen-id.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { getApLock } from "@/misc/app-lock.js"; -import { createMessage } from "@/services/messages/create.js"; -import { parseAudience } from "../audience.js"; -import { extractApMentions } from "./mention.js"; -import DbResolver from "../db-resolver.js"; -import { StatusError } from "@/misc/fetch.js"; -import { shouldBlockInstance } from "@/misc/should-block-instance.js"; - -const logger = apLogger; - -export function validateNote(object: any, uri: string) { - const expectHost = extractDbHost(uri); - - if (object == null) { - return new Error("invalid Note: object is null"); - } - - if (!validPost.includes(getApType(object))) { - return new Error(`invalid Note: invalid object type ${getApType(object)}`); - } - - if (object.id && extractDbHost(object.id) !== expectHost) { - return new Error( - `invalid Note: id has different host. expected: ${expectHost}, actual: ${extractDbHost( - object.id, - )}`, - ); - } - - if ( - object.attributedTo && - extractDbHost(getOneApId(object.attributedTo)) !== expectHost - ) { - return new Error( - `invalid Note: attributedTo has different host. expected: ${expectHost}, actual: ${extractDbHost( - object.attributedTo, - )}`, - ); - } - - return null; -} - -/** - * Fetch Notes. - * - * If the target Note is registered in Calckey, it will be returned. - */ -export async function fetchNote( - object: string | IObject, -): Promise<Note | null> { - const dbResolver = new DbResolver(); - return await dbResolver.getNoteFromApId(object); -} - -/** - * Create a Note. - */ -export async function createNote( - value: string | IObject, - resolver?: Resolver, - silent = false, -): Promise<Note | null> { - if (resolver == null) resolver = new Resolver(); - - const object: any = await resolver.resolve(value); - - const entryUri = getApId(value); - const err = validateNote(object, entryUri); - if (err) { - logger.error(`${err.message}`, { - resolver: { - history: resolver.getHistory(), - }, - value: value, - object: object, - }); - throw new Error("invalid note"); - } - - const note: IPost = object; - - if (note.id && !note.id.startsWith("https://")) { - throw new Error(`unexpected schema of note.id: ${note.id}`); - } - - const url = getOneApHrefNullable(note.url); - - if (url && !url.startsWith("https://")) { - throw new Error(`unexpected schema of note url: ${url}`); - } - - logger.debug(`Note fetched: ${JSON.stringify(note, null, 2)}`); - logger.info(`Creating the Note: ${note.id}`); - - // Skip if note is made before 2007 (1yr before Fedi was created) - // OR skip if note is made 3 days in advance - if (note.published) { - const DateChecker = new Date(note.published); - const FutureCheck = new Date(); - FutureCheck.setDate(FutureCheck.getDate() + 3); // Allow some wiggle room for misconfigured hosts - if (DateChecker.getFullYear() < 2007) { - logger.warn( - "Note somehow made before Activitypub was created; discarding", - ); - return null; - } - if (DateChecker > FutureCheck) { - logger.warn("Note somehow made after today; discarding"); - return null; - } - } - - // Fetch author - const actor = (await resolvePerson( - getOneApId(note.attributedTo), - resolver, - )) as CacheableRemoteUser; - - // Skip if author is suspended. - if (actor.isSuspended) { - logger.debug( - `User ${actor.usernameLower}@${actor.host} suspended; discarding.`, - ); - return null; - } - - const noteAudience = await parseAudience(actor, note.to, note.cc); - let visibility = noteAudience.visibility; - const visibleUsers = noteAudience.visibleUsers; - - // If Audience (to, cc) was not specified - if (visibility === "specified" && visibleUsers.length === 0) { - if (typeof value === "string") { - // If the input is a string, GET occurs in resolver - // Public if you can GET anonymously from here - visibility = "public"; - } - } - - let isTalk = note._misskey_talk && visibility === "specified"; - - const apMentions = await extractApMentions(note.tag); - const apHashtags = await extractApHashtags(note.tag); - - // Attachments - // TODO: attachmentは必ずしもImageではない - // TODO: attachmentは必ずしも配列ではない - // Noteがsensitiveなら添付もsensitiveにする - const limit = promiseLimit(2); - - note.attachment = Array.isArray(note.attachment) - ? note.attachment - : note.attachment - ? [note.attachment] - : []; - const files = note.attachment.map( - (attach) => (attach.sensitive = note.sensitive), - ) - ? ( - await Promise.all( - note.attachment.map( - (x) => limit(() => resolveImage(actor, x)) as Promise<DriveFile>, - ), - ) - ).filter((image) => image != null) - : []; - - // Reply - const reply: Note | null = note.inReplyTo - ? await resolveNote(note.inReplyTo, resolver) - .then((x) => { - if (x == null) { - logger.warn("Specified inReplyTo, but nout found"); - throw new Error("inReplyTo not found"); - } else { - return x; - } - }) - .catch(async (e) => { - // トークだったらinReplyToのエラーは無視 - const uri = getApId(note.inReplyTo); - if (uri.startsWith(`${config.url}/`)) { - const id = uri.split("/").pop(); - const talk = await MessagingMessages.findOneBy({ id }); - if (talk) { - isTalk = true; - return null; - } - } - - logger.warn( - `Error in inReplyTo ${note.inReplyTo} - ${e.statusCode || e}`, - ); - throw e; - }) - : null; - - // Quote - let quote: Note | undefined | null; - - if (note._misskey_quote || note.quoteUrl || note.quoteUri) { - const tryResolveNote = async ( - uri: string, - ): Promise< - | { - status: "ok"; - res: Note | null; - } - | { - status: "permerror" | "temperror"; - } - > => { - if (typeof uri !== "string" || !uri.match(/^https?:/)) - return { status: "permerror" }; - try { - const res = await resolveNote(uri); - if (res) { - return { - status: "ok", - res, - }; - } else { - return { - status: "permerror", - }; - } - } catch (e) { - return { - status: - e instanceof StatusError && e.isClientError - ? "permerror" - : "temperror", - }; - } - }; - - const uris = unique( - [note._misskey_quote, note.quoteUrl, note.quoteUri].filter( - (x): x is string => typeof x === "string", - ), - ); - const results = await Promise.all(uris.map((uri) => tryResolveNote(uri))); - - quote = results - .filter((x): x is { status: "ok"; res: Note | null } => x.status === "ok") - .map((x) => x.res) - .find((x) => x); - if (!quote) { - if (results.some((x) => x.status === "temperror")) { - throw new Error("quote resolve failed"); - } - } - } - - const cw = note.summary === "" ? null : note.summary; - - // Text parsing - let text: string | null = null; - if ( - note.source?.mediaType === "text/x.misskeymarkdown" && - typeof note.source?.content === "string" - ) { - text = note.source.content; - } else if (typeof note._misskey_content !== "undefined") { - text = note._misskey_content; - } else if (typeof note.content === "string") { - text = htmlToMfm(note.content, note.tag); - } - - // vote - if (reply?.hasPoll) { - const poll = await Polls.findOneByOrFail({ noteId: reply.id }); - - const tryCreateVote = async ( - name: string, - index: number, - ): Promise<null> => { - if (poll.expiresAt && Date.now() > new Date(poll.expiresAt).getTime()) { - logger.warn( - `vote to expired poll from AP: actor=${actor.username}@${actor.host}, note=${note.id}, choice=${name}`, - ); - } else if (index >= 0) { - logger.info( - `vote from AP: actor=${actor.username}@${actor.host}, note=${note.id}, choice=${name}`, - ); - await vote(actor, reply, index); - - // リモートフォロワーにUpdate配信 - deliverQuestionUpdate(reply.id); - } - return null; - }; - - if (note.name) { - return await tryCreateVote( - note.name, - poll.choices.findIndex((x) => x === note.name), - ); - } - } - - const emojis = await extractEmojis(note.tag || [], actor.host).catch((e) => { - logger.info(`extractEmojis: ${e}`); - return [] as Emoji[]; - }); - - const apEmojis = emojis.map((emoji) => emoji.name); - - const poll = await extractPollFromQuestion(note, resolver).catch( - () => undefined, - ); - - if (isTalk) { - for (const recipient of visibleUsers) { - await createMessage( - actor, - recipient, - undefined, - text || undefined, - files && files.length > 0 ? files[0] : null, - object.id, - ); - return null; - } - } - - return await post( - actor, - { - createdAt: note.published ? new Date(note.published) : null, - files, - reply, - renote: quote, - name: note.name, - cw, - text, - localOnly: false, - visibility, - visibleUsers, - apMentions, - apHashtags, - apEmojis, - poll, - uri: note.id, - url: url, - }, - silent, - ); -} - -/** - * Resolve Note. - * - * If the target Note is registered in Calckey, return it, otherwise - * Fetch from remote server, register with Calckey and return it. - */ -export async function resolveNote( - value: string | IObject, - resolver?: Resolver, -): Promise<Note | null> { - const uri = typeof value === "string" ? value : value.id; - if (uri == null) throw new Error("missing uri"); - - // Abort if origin host is blocked - if (await shouldBlockInstance(extractDbHost(uri))) - throw new StatusError( - "host blocked", - 451, - `host ${extractDbHost(uri)} is blocked`, - ); - - const unlock = await getApLock(uri); - - try { - //#region Returns if already registered with this server - const exist = await fetchNote(uri); - - if (exist) { - return exist; - } - //#endregion - - if (uri.startsWith(config.url)) { - throw new StatusError( - "cannot resolve local note", - 400, - "cannot resolve local note", - ); - } - - // Fetch from remote server and register - // If the attached `Note` Object is specified here instead of the uri, the note will be generated without going through the server fetch. - // Since the attached Note Object may be disguised, always specify the uri and fetch it from the server. - return await createNote(uri, resolver, true); - } finally { - unlock(); - } -} - -export async function extractEmojis( - tags: IObject | IObject[], - host: string, -): Promise<Emoji[]> { - host = toPuny(host); - - if (!tags) return []; - - const eomjiTags = toArray(tags).filter(isEmoji); - - return await Promise.all( - eomjiTags.map(async (tag) => { - const name = tag.name!.replace(/^:/, "").replace(/:$/, ""); - tag.icon = toSingle(tag.icon); - - const exists = await Emojis.findOneBy({ - host, - name, - }); - - if (exists) { - if ( - (tag.updated != null && exists.updatedAt == null) || - (tag.id != null && exists.uri == null) || - (tag.updated != null && - exists.updatedAt != null && - new Date(tag.updated) > exists.updatedAt) || - tag.icon!.url !== exists.originalUrl - ) { - await Emojis.update( - { - host, - name, - }, - { - uri: tag.id, - originalUrl: tag.icon!.url, - publicUrl: tag.icon!.url, - updatedAt: new Date(), - }, - ); - - return (await Emojis.findOneBy({ - host, - name, - })) as Emoji; - } - - return exists; - } - - logger.info(`register emoji host=${host}, name=${name}`); - - return await Emojis.insert({ - id: genId(), - host, - name, - uri: tag.id, - originalUrl: tag.icon!.url, - publicUrl: tag.icon!.url, - updatedAt: new Date(), - aliases: [], - } as Partial<Emoji>).then((x) => - Emojis.findOneByOrFail(x.identifiers[0]), - ); - }), - ); -} diff --git a/packages/backend/src/remote/activitypub/models/person.ts b/packages/backend/src/remote/activitypub/models/person.ts deleted file mode 100644 index 877f5f3323..0000000000 --- a/packages/backend/src/remote/activitypub/models/person.ts +++ /dev/null @@ -1,698 +0,0 @@ -import { URL } from "node:url"; -import promiseLimit from "promise-limit"; - -import config from "@/config/index.js"; -import { registerOrFetchInstanceDoc } from "@/services/register-or-fetch-instance-doc.js"; -import type { Note } from "@/models/entities/note.js"; -import { updateUsertags } from "@/services/update-hashtag.js"; -import { - Users, - Instances, - DriveFiles, - Followings, - UserProfiles, - UserPublickeys, -} from "@/models/index.js"; -import type { IRemoteUser, CacheableUser } from "@/models/entities/user.js"; -import { User } from "@/models/entities/user.js"; -import type { Emoji } from "@/models/entities/emoji.js"; -import { UserNotePining } from "@/models/entities/user-note-pining.js"; -import { genId } from "@/misc/gen-id.js"; -import { instanceChart, usersChart } from "@/services/chart/index.js"; -import { UserPublickey } from "@/models/entities/user-publickey.js"; -import { isDuplicateKeyValueError } from "@/misc/is-duplicate-key-value-error.js"; -import { toPuny } from "@/misc/convert-host.js"; -import { UserProfile } from "@/models/entities/user-profile.js"; -import { toArray } from "@/prelude/array.js"; -import { fetchInstanceMetadata } from "@/services/fetch-instance-metadata.js"; -import { normalizeForSearch } from "@/misc/normalize-for-search.js"; -import { truncate } from "@/misc/truncate.js"; -import { StatusError } from "@/misc/fetch.js"; -import { uriPersonCache } from "@/services/user-cache.js"; -import { publishInternalEvent } from "@/services/stream.js"; -import { db } from "@/db/postgre.js"; -import { apLogger } from "../logger.js"; -import { htmlToMfm } from "../misc/html-to-mfm.js"; -import { fromHtml } from "../../../mfm/from-html.js"; -import type { IActor, IObject, IApPropertyValue } from "../type.js"; -import { - isCollectionOrOrderedCollection, - isCollection, - getApId, - getOneApHrefNullable, - isPropertyValue, - getApType, - isActor, -} from "../type.js"; -import Resolver from "../resolver.js"; -import { extractApHashtags } from "./tag.js"; -import { resolveNote, extractEmojis } from "./note.js"; -import { resolveImage } from "./image.js"; - -const logger = apLogger; - -const nameLength = 128; -const summaryLength = 2048; - -/** - * Validate and convert to actor object - * @param x Fetched object - * @param uri Fetch target URI - */ -function validateActor(x: IObject, uri: string): IActor { - const expectHost = toPuny(new URL(uri).hostname); - - if (x == null) { - throw new Error("invalid Actor: object is null"); - } - - if (!isActor(x)) { - throw new Error(`invalid Actor type '${x.type}'`); - } - - if (!(typeof x.id === "string" && x.id.length > 0)) { - throw new Error("invalid Actor: wrong id"); - } - - if (!(typeof x.inbox === "string" && x.inbox.length > 0)) { - throw new Error("invalid Actor: wrong inbox"); - } - - if ( - !( - typeof x.preferredUsername === "string" && - x.preferredUsername.length > 0 && - x.preferredUsername.length <= 128 && - /^\w([\w-.]*\w)?$/.test(x.preferredUsername) - ) - ) { - throw new Error("invalid Actor: wrong username"); - } - - // These fields are only informational, and some AP software allows these - // fields to be very long. If they are too long, we cut them off. This way - // we can at least see these users and their activities. - if (x.name) { - if (!(typeof x.name === "string" && x.name.length > 0)) { - throw new Error("invalid Actor: wrong name"); - } - x.name = truncate(x.name, nameLength); - } - if (x.summary) { - if (!(typeof x.summary === "string" && x.summary.length > 0)) { - throw new Error("invalid Actor: wrong summary"); - } - x.summary = truncate(x.summary, summaryLength); - } - - const idHost = toPuny(new URL(x.id!).hostname); - if (idHost !== expectHost) { - throw new Error("invalid Actor: id has different host"); - } - - if (x.publicKey) { - if (typeof x.publicKey.id !== "string") { - throw new Error("invalid Actor: publicKey.id is not a string"); - } - - const publicKeyIdHost = toPuny(new URL(x.publicKey.id).hostname); - if (publicKeyIdHost !== expectHost) { - throw new Error("invalid Actor: publicKey.id has different host"); - } - } - - return x; -} - -/** - * Fetch a Person. - * - * If the target Person is registered in Calckey, it will be returned. - */ -export async function fetchPerson( - uri: string, - resolver?: Resolver, -): Promise<CacheableUser | null> { - if (typeof uri !== "string") throw new Error("uri is not string"); - - const cached = uriPersonCache.get(uri); - if (cached) return cached; - - // Fetch from the database if the URI points to this server - if (uri.startsWith(`${config.url}/`)) { - const id = uri.split("/").pop(); - const u = await Users.findOneBy({ id }); - if (u) uriPersonCache.set(uri, u); - return u; - } - - //#region Returns if already registered with this server - const exist = await Users.findOneBy({ uri }); - - if (exist) { - uriPersonCache.set(uri, exist); - return exist; - } - //#endregion - - return null; -} - -/** - * Create Person. - */ -export async function createPerson( - uri: string, - resolver?: Resolver, -): Promise<User> { - if (typeof uri !== "string") throw new Error("uri is not string"); - - if (uri.startsWith(config.url)) { - throw new StatusError( - "cannot resolve local user", - 400, - "cannot resolve local user", - ); - } - - if (resolver == null) resolver = new Resolver(); - - const object = (await resolver.resolve(uri)) as any; - - const person = validateActor(object, uri); - - logger.info(`Creating the Person: ${person.id}`); - - const host = toPuny(new URL(object.id).hostname); - - const { fields } = analyzeAttachments(person.attachment || []); - - const tags = extractApHashtags(person.tag) - .map((tag) => normalizeForSearch(tag)) - .splice(0, 32); - - const isBot = getApType(object) === "Service"; - - const bday = person["vcard:bday"]?.match(/^\d{4}-\d{2}-\d{2}/); - - const url = getOneApHrefNullable(person.url); - - if (url && !url.startsWith("https://")) { - throw new Error(`unexpected schema of person url: ${url}`); - } - - let followersCount: number | undefined; - - if (typeof person.followers === "string") { - try { - let data = await fetch(person.followers, { - headers: { Accept: "application/json" }, - }); - let json_data = JSON.parse(await data.text()); - - followersCount = json_data.totalItems; - } catch { - followersCount = undefined; - } - } - - let followingCount: number | undefined; - - if (typeof person.following === "string") { - try { - let data = await fetch(person.following, { - headers: { Accept: "application/json" }, - }); - let json_data = JSON.parse(await data.text()); - - followingCount = json_data.totalItems; - } catch (e) { - followingCount = undefined; - } - } - - // Create user - let user: IRemoteUser; - try { - // Start transaction - await db.transaction(async (transactionalEntityManager) => { - user = (await transactionalEntityManager.save( - new User({ - id: genId(), - avatarId: null, - bannerId: null, - createdAt: new Date(), - lastFetchedAt: new Date(), - name: truncate(person.name, nameLength), - isLocked: !!person.manuallyApprovesFollowers, - movedToUri: person.movedTo, - alsoKnownAs: person.alsoKnownAs, - isExplorable: !!person.discoverable, - username: person.preferredUsername, - usernameLower: person.preferredUsername!.toLowerCase(), - host, - inbox: person.inbox, - sharedInbox: - person.sharedInbox || - (person.endpoints ? person.endpoints.sharedInbox : undefined), - followersUri: person.followers - ? getApId(person.followers) - : undefined, - followersCount: - followersCount !== undefined - ? followersCount - : person.followers && - typeof person.followers !== "string" && - isCollectionOrOrderedCollection(person.followers) - ? person.followers.totalItems - : undefined, - followingCount: - followingCount !== undefined - ? followingCount - : person.following && - typeof person.following !== "string" && - isCollectionOrOrderedCollection(person.following) - ? person.following.totalItems - : undefined, - featured: person.featured ? getApId(person.featured) : undefined, - uri: person.id, - tags, - isBot, - isCat: (person as any).isCat === true, - showTimelineReplies: false, - }), - )) as IRemoteUser; - - await transactionalEntityManager.save( - new UserProfile({ - userId: user.id, - description: person.summary - ? htmlToMfm(truncate(person.summary, summaryLength), person.tag) - : null, - url: url, - fields, - birthday: bday ? bday[0] : null, - location: person["vcard:Address"] || null, - userHost: host, - }), - ); - - if (person.publicKey) { - await transactionalEntityManager.save( - new UserPublickey({ - userId: user.id, - keyId: person.publicKey.id, - keyPem: person.publicKey.publicKeyPem, - }), - ); - } - }); - } catch (e) { - // duplicate key error - if (isDuplicateKeyValueError(e)) { - // /users/@a => /users/:id Corresponds to an error that may occur when the input is an alias like - const u = await Users.findOneBy({ - uri: person.id, - }); - - if (u) { - user = u as IRemoteUser; - } else { - throw new Error("already registered"); - } - } else { - logger.error(e instanceof Error ? e : new Error(e as string)); - throw e; - } - } - - // Register host - registerOrFetchInstanceDoc(host).then((i) => { - Instances.increment({ id: i.id }, "usersCount", 1); - instanceChart.newUser(i.host); - fetchInstanceMetadata(i); - }); - - usersChart.update(user!, true); - - // Hashtag update - updateUsertags(user!, tags); - - //#region Fetch avatar and header image - const [avatar, banner] = await Promise.all( - [person.icon, person.image].map((img) => - img == null - ? Promise.resolve(null) - : resolveImage(user!, img).catch(() => null), - ), - ); - - const avatarId = avatar ? avatar.id : null; - const bannerId = banner ? banner.id : null; - - await Users.update(user!.id, { - avatarId, - bannerId, - }); - - user!.avatarId = avatarId; - user!.bannerId = bannerId; - //#endregion - - //#region Get custom emoji - const emojis = await extractEmojis(person.tag || [], host).catch((e) => { - logger.info(`extractEmojis: ${e}`); - return [] as Emoji[]; - }); - - const emojiNames = emojis.map((emoji) => emoji.name); - - await Users.update(user!.id, { - emojis: emojiNames, - }); - //#endregion - - await updateFeatured(user!.id, resolver).catch((err) => logger.error(err)); - - return user!; -} - -/** - * Update Person data from remote. - * If the target Person is not registered in Calckey, it is ignored. - * @param uri URI of Person - * @param resolver Resolver - * @param hint Hint of Person object (If this value is a valid Person, it is used for updating without Remote resolve) - */ -export async function updatePerson( - uri: string, - resolver?: Resolver | null, - hint?: IObject, -): Promise<void> { - if (typeof uri !== "string") throw new Error("uri is not string"); - - // Skip if the URI points to this server - if (uri.startsWith(`${config.url}/`)) { - return; - } - - //#region Already registered on this server? - const exist = (await Users.findOneBy({ uri })) as IRemoteUser; - - if (exist == null) { - return; - } - //#endregion - - if (resolver == null) resolver = new Resolver(); - - const object = hint || (await resolver.resolve(uri)); - - const person = validateActor(object, uri); - - logger.info(`Updating the Person: ${person.id}`); - - // Fetch avatar and header image - const [avatar, banner] = await Promise.all( - [person.icon, person.image].map((img) => - img == null - ? Promise.resolve(null) - : resolveImage(exist, img).catch(() => null), - ), - ); - - // Custom pictogram acquisition - const emojis = await extractEmojis(person.tag || [], exist.host).catch( - (e) => { - logger.info(`extractEmojis: ${e}`); - return [] as Emoji[]; - }, - ); - - const emojiNames = emojis.map((emoji) => emoji.name); - - const { fields } = analyzeAttachments(person.attachment || []); - - const tags = extractApHashtags(person.tag) - .map((tag) => normalizeForSearch(tag)) - .splice(0, 32); - - const bday = person["vcard:bday"]?.match(/^\d{4}-\d{2}-\d{2}/); - - const url = getOneApHrefNullable(person.url); - - if (url && !url.startsWith("https://")) { - throw new Error(`unexpected schema of person url: ${url}`); - } - - let followersCount: number | undefined; - - if (typeof person.followers === "string") { - try { - let data = await fetch(person.followers, { - headers: { Accept: "application/json" }, - }); - let json_data = JSON.parse(await data.text()); - - followersCount = json_data.totalItems; - } catch { - followersCount = undefined; - } - } - - let followingCount: number | undefined; - - if (typeof person.following === "string") { - try { - let data = await fetch(person.following, { - headers: { Accept: "application/json" }, - }); - let json_data = JSON.parse(await data.text()); - - followingCount = json_data.totalItems; - } catch { - followingCount = undefined; - } - } - - const updates = { - lastFetchedAt: new Date(), - inbox: person.inbox, - sharedInbox: - person.sharedInbox || - (person.endpoints ? person.endpoints.sharedInbox : undefined), - followersUri: person.followers ? getApId(person.followers) : undefined, - followersCount: - followersCount !== undefined - ? followersCount - : person.followers && - typeof person.followers !== "string" && - isCollectionOrOrderedCollection(person.followers) - ? person.followers.totalItems - : undefined, - followingCount: - followingCount !== undefined - ? followingCount - : person.following && - typeof person.following !== "string" && - isCollectionOrOrderedCollection(person.following) - ? person.following.totalItems - : undefined, - featured: person.featured, - emojis: emojiNames, - name: truncate(person.name, nameLength), - tags, - isBot: getApType(object) === "Service", - isCat: (person as any).isCat === true, - isLocked: !!person.manuallyApprovesFollowers, - movedToUri: person.movedTo || null, - alsoKnownAs: person.alsoKnownAs || null, - isExplorable: !!person.discoverable, - } as Partial<User>; - - if (avatar) { - updates.avatarId = avatar.id; - } - - if (banner) { - updates.bannerId = banner.id; - } - - // Update user - await Users.update(exist.id, updates); - - if (person.publicKey) { - await UserPublickeys.update( - { userId: exist.id }, - { - keyId: person.publicKey.id, - keyPem: person.publicKey.publicKeyPem, - }, - ); - } - - await UserProfiles.update( - { userId: exist.id }, - { - url: url, - fields, - description: person.summary - ? htmlToMfm(truncate(person.summary, summaryLength), person.tag) - : null, - birthday: bday ? bday[0] : null, - location: person["vcard:Address"] || null, - }, - ); - - publishInternalEvent("remoteUserUpdated", { id: exist.id }); - - // Hashtag Update - updateUsertags(exist, tags); - - // If the user in question is a follower, followers will also be updated. - await Followings.update( - { - followerId: exist.id, - }, - { - followerSharedInbox: - person.sharedInbox || - (person.endpoints ? person.endpoints.sharedInbox : undefined), - }, - ); - - await updateFeatured(exist.id, resolver).catch((err) => logger.error(err)); -} - -/** - * Resolve Person. - * - * If the target person is registered in Calckey, it returns it; - * otherwise, it fetches it from the remote server, registers it in Calckey, and returns it. - */ -export async function resolvePerson( - uri: string, - resolver?: Resolver, -): Promise<CacheableUser> { - if (typeof uri !== "string") throw new Error("uri is not string"); - - //#region If already registered on this server, return it. - const exist = await fetchPerson(uri); - - if (exist) { - return exist; - } - //#endregion - - // Fetched from remote server and registered - if (resolver == null) resolver = new Resolver(); - return await createPerson(uri, resolver); -} - -const services: { - [x: string]: (id: string, username: string) => any; -} = { - "misskey:authentication:twitter": (userId, screenName) => ({ - userId, - screenName, - }), - "misskey:authentication:github": (id, login) => ({ id, login }), - "misskey:authentication:discord": (id, name) => $discord(id, name), -}; - -const $discord = (id: string, name: string) => { - if (typeof name !== "string") { - name = "unknown#0000"; - } - const [username, discriminator] = name.split("#"); - return { id, username, discriminator }; -}; - -function addService(target: { [x: string]: any }, source: IApPropertyValue) { - const service = services[source.name]; - - if (typeof source.value !== "string") { - source.value = "unknown"; - } - - const [id, username] = source.value.split("@"); - - if (service) { - target[source.name.split(":")[2]] = service(id, username); - } -} - -export function analyzeAttachments( - attachments: IObject | IObject[] | undefined, -) { - const fields: { - name: string; - value: string; - }[] = []; - const services: { [x: string]: any } = {}; - - if (Array.isArray(attachments)) { - for (const attachment of attachments.filter(isPropertyValue)) { - if (isPropertyValue(attachment.identifier)) { - addService(services, attachment.identifier); - } else { - fields.push({ - name: attachment.name, - value: fromHtml(attachment.value), - }); - } - } - } - - return { fields, services }; -} - -export async function updateFeatured(userId: User["id"], resolver?: Resolver) { - const user = await Users.findOneByOrFail({ id: userId }); - if (!Users.isRemoteUser(user)) return; - if (!user.featured) return; - - logger.info(`Updating the featured: ${user.uri}`); - - if (resolver == null) resolver = new Resolver(); - - // Resolve to (Ordered)Collection Object - const collection = await resolver.resolveCollection(user.featured); - if (!isCollectionOrOrderedCollection(collection)) - throw new Error("Object is not Collection or OrderedCollection"); - - // Resolve to Object(may be Note) arrays - const unresolvedItems = isCollection(collection) - ? collection.items - : collection.orderedItems; - const items = await Promise.all( - toArray(unresolvedItems).map((x) => resolver.resolve(x)), - ); - - // Resolve and regist Notes - const limit = promiseLimit<Note | null>(2); - const featuredNotes = await Promise.all( - items - .filter((item) => getApType(item) === "Note") // TODO: Maybe it doesn't have to be a Note. - .slice(0, 5) - .map((item) => limit(() => resolveNote(item, resolver))), - ); - - await db.transaction(async (transactionalEntityManager) => { - await transactionalEntityManager.delete(UserNotePining, { - userId: user.id, - }); - - // For now, generate the id at a different time and maintain the order. - let td = 0; - for (const note of featuredNotes.filter((note) => note != null)) { - td -= 1000; - transactionalEntityManager.insert(UserNotePining, { - id: genId(new Date(Date.now() + td)), - createdAt: new Date(), - userId: user.id, - noteId: note!.id, - }); - } - }); -} diff --git a/packages/backend/src/remote/activitypub/models/question.ts b/packages/backend/src/remote/activitypub/models/question.ts deleted file mode 100644 index 520b9fee94..0000000000 --- a/packages/backend/src/remote/activitypub/models/question.ts +++ /dev/null @@ -1,97 +0,0 @@ -import config from "@/config/index.js"; -import Resolver from "../resolver.js"; -import type { IObject, IQuestion } from "../type.js"; -import { isQuestion } from "../type.js"; -import { apLogger } from "../logger.js"; -import { Notes, Polls } from "@/models/index.js"; -import type { IPoll } from "@/models/entities/poll.js"; - -export async function extractPollFromQuestion( - source: string | IObject, - resolver?: Resolver, -): Promise<IPoll> { - if (resolver == null) resolver = new Resolver(); - - const question = await resolver.resolve(source); - - if (!isQuestion(question)) { - throw new Error("invalid type"); - } - - const multiple = !question.oneOf; - const expiresAt = question.endTime - ? new Date(question.endTime) - : question.closed - ? new Date(question.closed) - : null; - - if (multiple && !question.anyOf) { - throw new Error("invalid question"); - } - - const choices = question[multiple ? "anyOf" : "oneOf"]!.map( - (x, i) => x.name!, - ); - - const votes = question[multiple ? "anyOf" : "oneOf"]!.map( - (x, i) => x.replies?.totalItems || x._misskey_votes || 0, - ); - - return { - choices, - votes, - multiple, - expiresAt, - }; -} - -/** - * Update votes of Question - * @param uri URI of AP Question object - * @returns true if updated - */ -export async function updateQuestion(value: any, resolver?: Resolver) { - const uri = typeof value === "string" ? value : value.id; - - // Skip if URI points to this server - if (uri.startsWith(`${config.url}/`)) throw new Error("uri points local"); - - //#region Already registered with this server? - const note = await Notes.findOneBy({ uri }); - if (note == null) throw new Error("Question is not registed"); - - const poll = await Polls.findOneBy({ noteId: note.id }); - if (poll == null) throw new Error("Question is not registed"); - //#endregion - - // resolve new Question object - if (resolver == null) resolver = new Resolver(); - const question = (await resolver.resolve(value)) as IQuestion; - apLogger.debug(`fetched question: ${JSON.stringify(question, null, 2)}`); - - if (question.type !== "Question") throw new Error("object is not a Question"); - - const apChoices = question.oneOf || question.anyOf; - - let changed = false; - - for (const choice of poll.choices) { - const oldCount = poll.votes[poll.choices.indexOf(choice)]; - const newCount = apChoices!.filter((ap) => ap.name === choice)[0].replies! - .totalItems; - - if (oldCount !== newCount) { - changed = true; - poll.votes[poll.choices.indexOf(choice)] = newCount; - } - } - - await Polls.update( - { noteId: note.id }, - { - votes: poll.votes, - }, - ); - - return changed; -} diff --git a/packages/backend/src/remote/activitypub/models/tag.ts b/packages/backend/src/remote/activitypub/models/tag.ts deleted file mode 100644 index 537cdecbd5..0000000000 --- a/packages/backend/src/remote/activitypub/models/tag.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { toArray } from "@/prelude/array.js"; -import type { IObject, IApHashtag } from "../type.js"; -import { isHashtag } from "../type.js"; - -export function extractApHashtags( - tags: IObject | IObject[] | null | undefined, -) { - if (tags == null) return []; - - const hashtags = extractApHashtagObjects(tags); - - return hashtags - .map((tag) => { - const m = tag.name.match(/^#(.+)/); - return m ? m[1] : null; - }) - .filter((x): x is string => x != null); -} - -export function extractApHashtagObjects( - tags: IObject | IObject[] | null | undefined, -): IApHashtag[] { - if (tags == null) return []; - return toArray(tags).filter(isHashtag); -} diff --git a/packages/backend/src/remote/activitypub/perform.ts b/packages/backend/src/remote/activitypub/perform.ts deleted file mode 100644 index 0d2cdb4a5e..0000000000 --- a/packages/backend/src/remote/activitypub/perform.ts +++ /dev/null @@ -1,23 +0,0 @@ -import type { IObject } from "./type.js"; -import type { CacheableRemoteUser } from "@/models/entities/user.js"; -import { performActivity } from "./kernel/index.js"; -import { updatePerson } from "./models/person.js"; - -export default async ( - actor: CacheableRemoteUser, - activity: IObject, -): Promise<void> => { - await performActivity(actor, activity); - - // Update the remote user information if it is out of date - if (actor.uri) { - if ( - actor.lastFetchedAt == null || - Date.now() - actor.lastFetchedAt.getTime() > 1000 * 60 * 60 * 24 - ) { - setImmediate(() => { - updatePerson(actor.uri!); - }); - } - } -}; diff --git a/packages/backend/src/remote/activitypub/renderer/accept.ts b/packages/backend/src/remote/activitypub/renderer/accept.ts deleted file mode 100644 index fd145dcf97..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/accept.ts +++ /dev/null @@ -1,8 +0,0 @@ -import config from "@/config/index.js"; -import type { User } from "@/models/entities/user.js"; - -export default (object: any, user: { id: User["id"]; host: null }) => ({ - type: "Accept", - actor: `${config.url}/users/${user.id}`, - object, -}); diff --git a/packages/backend/src/remote/activitypub/renderer/add.ts b/packages/backend/src/remote/activitypub/renderer/add.ts deleted file mode 100644 index d8203ac1ea..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/add.ts +++ /dev/null @@ -1,9 +0,0 @@ -import config from "@/config/index.js"; -import type { ILocalUser } from "@/models/entities/user.js"; - -export default (user: ILocalUser, target: any, object: any) => ({ - type: "Add", - actor: `${config.url}/users/${user.id}`, - target, - object, -}); diff --git a/packages/backend/src/remote/activitypub/renderer/announce.ts b/packages/backend/src/remote/activitypub/renderer/announce.ts deleted file mode 100644 index 1fd1842acf..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/announce.ts +++ /dev/null @@ -1,37 +0,0 @@ -import config from "@/config/index.js"; -import type { Note } from "@/models/entities/note.js"; - -export default (object: any, note: Note) => { - const attributedTo = `${config.url}/users/${note.userId}`; - - const mentions = ( - JSON.parse(note.mentionedRemoteUsers) as IMentionedRemoteUsers - ).map((x) => x.uri); - - let to: string[] = []; - let cc: string[] = []; - - if (note.visibility === "public") { - to = ["https://www.w3.org/ns/activitystreams#Public"]; - cc = [`${attributedTo}/followers`]; - } else if (note.visibility === "home") { - to = [`${attributedTo}/followers`]; - cc = ["https://www.w3.org/ns/activitystreams#Public"]; - } else if (note.visibility === "followers") { - to = [`${attributedTo}/followers`]; - } else if (note.visibility === "specified") { - to = mentions; - } else { - return null; - } - - return { - id: `${config.url}/notes/${note.id}/activity`, - actor: `${config.url}/users/${note.userId}`, - type: "Announce", - published: note.createdAt.toISOString(), - to, - cc, - object, - }; -}; diff --git a/packages/backend/src/remote/activitypub/renderer/block.ts b/packages/backend/src/remote/activitypub/renderer/block.ts deleted file mode 100644 index c2ea267f38..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/block.ts +++ /dev/null @@ -1,20 +0,0 @@ -import config from "@/config/index.js"; -import type { Blocking } from "@/models/entities/blocking.js"; - -/** - * Renders a block into its ActivityPub representation. - * - * @param block The block to be rendered. The blockee relation must be loaded. - */ -export function renderBlock(block: Blocking) { - if (block.blockee?.uri == null) { - throw new Error("renderBlock: missing blockee uri"); - } - - return { - type: "Block", - id: `${config.url}/blocks/${block.id}`, - actor: `${config.url}/users/${block.blockerId}`, - object: block.blockee.uri, - }; -} diff --git a/packages/backend/src/remote/activitypub/renderer/create.ts b/packages/backend/src/remote/activitypub/renderer/create.ts deleted file mode 100644 index 857f5722cc..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/create.ts +++ /dev/null @@ -1,17 +0,0 @@ -import config from "@/config/index.js"; -import type { Note } from "@/models/entities/note.js"; - -export default (object: any, note: Note) => { - const activity = { - id: `${config.url}/notes/${note.id}/activity`, - actor: `${config.url}/users/${note.userId}`, - type: "Create", - published: note.createdAt.toISOString(), - object, - } as any; - - if (object.to) activity.to = object.to; - if (object.cc) activity.cc = object.cc; - - return activity; -}; diff --git a/packages/backend/src/remote/activitypub/renderer/delete.ts b/packages/backend/src/remote/activitypub/renderer/delete.ts deleted file mode 100644 index 70bdc34922..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/delete.ts +++ /dev/null @@ -1,9 +0,0 @@ -import config from "@/config/index.js"; -import type { User } from "@/models/entities/user.js"; - -export default (object: any, user: { id: User["id"]; host: null }) => ({ - type: "Delete", - actor: `${config.url}/users/${user.id}`, - object, - published: new Date().toISOString(), -}); diff --git a/packages/backend/src/remote/activitypub/renderer/document.ts b/packages/backend/src/remote/activitypub/renderer/document.ts deleted file mode 100644 index 1c2ca89d94..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/document.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { DriveFile } from "@/models/entities/drive-file.js"; -import { DriveFiles } from "@/models/index.js"; - -export default (file: DriveFile) => ({ - type: "Document", - mediaType: file.type, - url: DriveFiles.getPublicUrl(file), - name: file.comment, -}); diff --git a/packages/backend/src/remote/activitypub/renderer/emoji.ts b/packages/backend/src/remote/activitypub/renderer/emoji.ts deleted file mode 100644 index 3d9b8cd55b..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/emoji.ts +++ /dev/null @@ -1,17 +0,0 @@ -import config from "@/config/index.js"; -import type { Emoji } from "@/models/entities/emoji.js"; - -export default (emoji: Emoji) => ({ - id: `${config.url}/emojis/${emoji.name}`, - type: "Emoji", - name: `:${emoji.name}:`, - updated: - emoji.updatedAt != null - ? emoji.updatedAt.toISOString() - : new Date().toISOString, - icon: { - type: "Image", - mediaType: emoji.type || "image/png", - url: emoji.publicUrl || emoji.originalUrl, // || emoji.originalUrl してるのは後方互換性のため - }, -}); diff --git a/packages/backend/src/remote/activitypub/renderer/flag.ts b/packages/backend/src/remote/activitypub/renderer/flag.ts deleted file mode 100644 index f94d508e1d..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/flag.ts +++ /dev/null @@ -1,20 +0,0 @@ -import config from "@/config/index.js"; -import { IObject, IActivity } from "@/remote/activitypub/type.js"; -import type { ILocalUser } from "@/models/entities/user.js"; -import { IRemoteUser } from "@/models/entities/user.js"; -import { getInstanceActor } from "@/services/instance-actor.js"; - -// to anonymise reporters, the reporting actor must be a system user -// object has to be a uri or array of uris -export const renderFlag = ( - user: ILocalUser, - object: [string], - content: string, -) => { - return { - type: "Flag", - actor: `${config.url}/users/${user.id}`, - content, - object, - }; -}; diff --git a/packages/backend/src/remote/activitypub/renderer/follow-relay.ts b/packages/backend/src/remote/activitypub/renderer/follow-relay.ts deleted file mode 100644 index ad7f05bf84..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/follow-relay.ts +++ /dev/null @@ -1,14 +0,0 @@ -import config from "@/config/index.js"; -import type { Relay } from "@/models/entities/relay.js"; -import type { ILocalUser } from "@/models/entities/user.js"; - -export function renderFollowRelay(relay: Relay, relayActor: ILocalUser) { - const follow = { - id: `${config.url}/activities/follow-relay/${relay.id}`, - type: "Follow", - actor: `${config.url}/users/${relayActor.id}`, - object: "https://www.w3.org/ns/activitystreams#Public", - }; - - return follow; -} diff --git a/packages/backend/src/remote/activitypub/renderer/follow-user.ts b/packages/backend/src/remote/activitypub/renderer/follow-user.ts deleted file mode 100644 index 22ee429ff6..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/follow-user.ts +++ /dev/null @@ -1,12 +0,0 @@ -import config from "@/config/index.js"; -import { Users } from "@/models/index.js"; -import type { User } from "@/models/entities/user.js"; - -/** - * Convert (local|remote)(Follower|Followee)ID to URL - * @param id Follower|Followee ID - */ -export default async function renderFollowUser(id: User["id"]): Promise<any> { - const user = await Users.findOneByOrFail({ id: id }); - return Users.isLocalUser(user) ? `${config.url}/users/${user.id}` : user.uri; -} diff --git a/packages/backend/src/remote/activitypub/renderer/follow.ts b/packages/backend/src/remote/activitypub/renderer/follow.ts deleted file mode 100644 index 3ff89c12aa..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/follow.ts +++ /dev/null @@ -1,22 +0,0 @@ -import config from "@/config/index.js"; -import type { User } from "@/models/entities/user.js"; -import { Users } from "@/models/index.js"; - -export default ( - follower: { id: User["id"]; host: User["host"]; uri: User["host"] }, - followee: { id: User["id"]; host: User["host"]; uri: User["host"] }, - requestId?: string, -) => { - const follow = { - id: requestId ?? `${config.url}/follows/${follower.id}/${followee.id}`, - type: "Follow", - actor: Users.isLocalUser(follower) - ? `${config.url}/users/${follower.id}` - : follower.uri, - object: Users.isLocalUser(followee) - ? `${config.url}/users/${followee.id}` - : followee.uri, - } as any; - - return follow; -}; diff --git a/packages/backend/src/remote/activitypub/renderer/hashtag.ts b/packages/backend/src/remote/activitypub/renderer/hashtag.ts deleted file mode 100644 index a00cd1ff5e..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/hashtag.ts +++ /dev/null @@ -1,7 +0,0 @@ -import config from "@/config/index.js"; - -export default (tag: string) => ({ - type: "Hashtag", - href: `${config.url}/tags/${encodeURIComponent(tag)}`, - name: `#${tag}`, -}); diff --git a/packages/backend/src/remote/activitypub/renderer/image.ts b/packages/backend/src/remote/activitypub/renderer/image.ts deleted file mode 100644 index 96183c7ad0..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/image.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { DriveFile } from "@/models/entities/drive-file.js"; -import { DriveFiles } from "@/models/index.js"; - -export default (file: DriveFile) => ({ - type: "Image", - url: DriveFiles.getPublicUrl(file), - sensitive: file.isSensitive, - name: file.comment, -}); diff --git a/packages/backend/src/remote/activitypub/renderer/index.ts b/packages/backend/src/remote/activitypub/renderer/index.ts deleted file mode 100644 index 7b98cf2d77..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/index.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { v4 as uuid } from "uuid"; -import config from "@/config/index.js"; -import { getUserKeypair } from "@/misc/keypair-store.js"; -import type { User } from "@/models/entities/user.js"; -import { LdSignature } from "../misc/ld-signature.js"; -import type { IActivity } from "../type.js"; - -export const renderActivity = (x: any): IActivity | null => { - if (x == null) return null; - - if (typeof x === "object" && x.id == null) { - x.id = `${config.url}/${uuid()}`; - } - - return Object.assign( - { - "@context": [ - "https://www.w3.org/ns/activitystreams", - "https://w3id.org/security/v1", - { - // as non-standards - manuallyApprovesFollowers: "as:manuallyApprovesFollowers", - movedToUri: "as:movedTo", - sensitive: "as:sensitive", - Hashtag: "as:Hashtag", - quoteUri: "fedibird:quoteUri", - quoteUrl: "as:quoteUrl", - // Mastodon - toot: "http://joinmastodon.org/ns#", - Emoji: "toot:Emoji", - featured: "toot:featured", - discoverable: "toot:discoverable", - // schema - schema: "http://schema.org#", - PropertyValue: "schema:PropertyValue", - value: "schema:value", - // Misskey - misskey: "https://misskey-hub.net/ns#", - _misskey_content: "misskey:_misskey_content", - _misskey_quote: "misskey:_misskey_quote", - _misskey_reaction: "misskey:_misskey_reaction", - _misskey_votes: "misskey:_misskey_votes", - _misskey_talk: "misskey:_misskey_talk", - isCat: "misskey:isCat", - // Fedibird - fedibird: "http://fedibird.com/ns#", - // vcard - vcard: "http://www.w3.org/2006/vcard/ns#", - }, - ], - }, - x, - ); -}; - -export const attachLdSignature = async ( - activity: any, - user: { id: User["id"]; host: null }, -): Promise<IActivity | null> => { - if (activity == null) return null; - - const keypair = await getUserKeypair(user.id); - - const ldSignature = new LdSignature(); - ldSignature.debug = false; - activity = await ldSignature.signRsaSignature2017( - activity, - keypair.privateKey, - `${config.url}/users/${user.id}#main-key`, - ); - - return activity; -}; diff --git a/packages/backend/src/remote/activitypub/renderer/key.ts b/packages/backend/src/remote/activitypub/renderer/key.ts deleted file mode 100644 index 084bb5361a..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/key.ts +++ /dev/null @@ -1,14 +0,0 @@ -import config from "@/config/index.js"; -import type { ILocalUser } from "@/models/entities/user.js"; -import type { UserKeypair } from "@/models/entities/user-keypair.js"; -import { createPublicKey } from "node:crypto"; - -export default (user: ILocalUser, key: UserKeypair, postfix?: string) => ({ - id: `${config.url}/users/${user.id}${postfix || "/publickey"}`, - type: "Key", - owner: `${config.url}/users/${user.id}`, - publicKeyPem: createPublicKey(key.publicKey).export({ - type: "spki", - format: "pem", - }), -}); diff --git a/packages/backend/src/remote/activitypub/renderer/like.ts b/packages/backend/src/remote/activitypub/renderer/like.ts deleted file mode 100644 index 53c66c5c92..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/like.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { IsNull } from "typeorm"; -import config from "@/config/index.js"; -import type { NoteReaction } from "@/models/entities/note-reaction.js"; -import type { Note } from "@/models/entities/note.js"; -import { Emojis } from "@/models/index.js"; -import renderEmoji from "./emoji.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; - -export const renderLike = async (noteReaction: NoteReaction, note: Note) => { - const reaction = noteReaction.reaction; - const meta = await fetchMeta(); - - const object = { - type: "Like", - id: `${config.url}/likes/${noteReaction.id}`, - actor: `${config.url}/users/${noteReaction.userId}`, - object: note.uri ? note.uri : `${config.url}/notes/${noteReaction.noteId}`, - ...(!meta.defaultReaction.includes(reaction) - ? { - content: reaction, - _misskey_reaction: reaction, - } - : {}), - } as any; - - if (reaction.startsWith(":")) { - const name = reaction.replace(/:/g, ""); - const emoji = await Emojis.findOneBy({ - name, - host: IsNull(), - }); - - if (emoji) object.tag = [renderEmoji(emoji)]; - } - - return object; -}; diff --git a/packages/backend/src/remote/activitypub/renderer/mention.ts b/packages/backend/src/remote/activitypub/renderer/mention.ts deleted file mode 100644 index e7f0435c16..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/mention.ts +++ /dev/null @@ -1,13 +0,0 @@ -import config from "@/config/index.js"; -import type { User, ILocalUser } from "@/models/entities/user.js"; -import { Users } from "@/models/index.js"; - -export default (mention: User) => ({ - type: "Mention", - href: Users.isRemoteUser(mention) - ? mention.uri - : `${config.url}/users/${(mention as ILocalUser).id}`, - name: Users.isRemoteUser(mention) - ? `@${mention.username}@${mention.host}` - : `@${(mention as ILocalUser).username}`, -}); diff --git a/packages/backend/src/remote/activitypub/renderer/note.ts b/packages/backend/src/remote/activitypub/renderer/note.ts deleted file mode 100644 index 2ad2fec9fb..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/note.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { In, IsNull } from "typeorm"; -import config from "@/config/index.js"; -import type { Note, IMentionedRemoteUsers } from "@/models/entities/note.js"; -import type { DriveFile } from "@/models/entities/drive-file.js"; -import { DriveFiles, Notes, Users, Emojis, Polls } from "@/models/index.js"; -import type { Emoji } from "@/models/entities/emoji.js"; -import type { Poll } from "@/models/entities/poll.js"; -import toHtml from "../misc/get-note-html.js"; -import renderEmoji from "./emoji.js"; -import renderMention from "./mention.js"; -import renderHashtag from "./hashtag.js"; -import renderDocument from "./document.js"; - -export default async function renderNote( - note: Note, - dive = true, - isTalk = false, -): Promise<Record<string, unknown>> { - const getPromisedFiles = async (ids: string[]) => { - if (!ids || ids.length === 0) return []; - const items = await DriveFiles.findBy({ id: In(ids) }); - return ids - .map((id) => items.find((item) => item.id === id)) - .filter((item) => item != null) as DriveFile[]; - }; - - let inReplyTo; - let inReplyToNote: Note | null; - - if (note.replyId) { - inReplyToNote = await Notes.findOneBy({ id: note.replyId }); - - if (inReplyToNote != null) { - const inReplyToUser = await Users.findOneBy({ id: inReplyToNote.userId }); - - if (inReplyToUser != null) { - if (inReplyToNote.uri) { - inReplyTo = inReplyToNote.uri; - } else { - if (dive) { - inReplyTo = await renderNote(inReplyToNote, false); - } else { - inReplyTo = `${config.url}/notes/${inReplyToNote.id}`; - } - } - } - } - } else { - inReplyTo = null; - } - - let quote; - - if (note.renoteId) { - const renote = await Notes.findOneBy({ id: note.renoteId }); - - if (renote) { - quote = renote.uri ? renote.uri : `${config.url}/notes/${renote.id}`; - } - } - - const attributedTo = `${config.url}/users/${note.userId}`; - - const mentions = ( - JSON.parse(note.mentionedRemoteUsers) as IMentionedRemoteUsers - ).map((x) => x.uri); - - let to: string[] = []; - let cc: string[] = []; - - if (note.visibility === "public") { - to = ["https://www.w3.org/ns/activitystreams#Public"]; - cc = [`${attributedTo}/followers`].concat(mentions); - } else if (note.visibility === "home") { - to = [`${attributedTo}/followers`]; - cc = ["https://www.w3.org/ns/activitystreams#Public"].concat(mentions); - } else if (note.visibility === "followers") { - to = [`${attributedTo}/followers`]; - cc = mentions; - } else { - to = mentions; - } - - const mentionedUsers = - note.mentions.length > 0 - ? await Users.findBy({ - id: In(note.mentions), - }) - : []; - - const hashtagTags = (note.tags || []).map((tag) => renderHashtag(tag)); - const mentionTags = mentionedUsers.map((u) => renderMention(u)); - - const files = await getPromisedFiles(note.fileIds); - - const text = note.text ?? ""; - let poll: Poll | null = null; - - if (note.hasPoll) { - poll = await Polls.findOneBy({ noteId: note.id }); - } - - let apText = text; - - if (quote) { - apText += `\n\nRE: ${quote}`; - } - - const summary = note.cw === "" ? String.fromCharCode(0x200b) : note.cw; - - const content = toHtml( - Object.assign({}, note, { - text: apText, - }), - ); - - const emojis = await getEmojis(note.emojis); - const apemojis = emojis.map((emoji) => renderEmoji(emoji)); - - const tag = [...hashtagTags, ...mentionTags, ...apemojis]; - - const asPoll = poll - ? { - type: "Question", - content: toHtml( - Object.assign({}, note, { - text: text, - }), - ), - [poll.expiresAt && poll.expiresAt < new Date() ? "closed" : "endTime"]: - poll.expiresAt, - [poll.multiple ? "anyOf" : "oneOf"]: poll.choices.map((text, i) => ({ - type: "Note", - name: text, - replies: { - type: "Collection", - totalItems: poll!.votes[i], - }, - })), - } - : {}; - - const asTalk = isTalk - ? { - _misskey_talk: true, - } - : {}; - - return { - id: `${config.url}/notes/${note.id}`, - type: "Note", - attributedTo, - summary, - content, - _misskey_content: text, - source: { - content: text, - mediaType: "text/x.misskeymarkdown", - }, - _misskey_quote: quote, - quoteUri: quote, - quoteUrl: quote, - published: note.createdAt.toISOString(), - to, - cc, - inReplyTo, - attachment: files.map(renderDocument), - sensitive: note.cw != null || files.some((file) => file.isSensitive), - tag, - ...asPoll, - ...asTalk, - }; -} - -export async function getEmojis(names: string[]): Promise<Emoji[]> { - if (names == null || names.length === 0) return []; - - const emojis = await Promise.all( - names.map((name) => - Emojis.findOneBy({ - name, - host: IsNull(), - }), - ), - ); - - return emojis.filter((emoji) => emoji != null) as Emoji[]; -} diff --git a/packages/backend/src/remote/activitypub/renderer/ordered-collection-page.ts b/packages/backend/src/remote/activitypub/renderer/ordered-collection-page.ts deleted file mode 100644 index 2275c9c94e..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/ordered-collection-page.ts +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Render OrderedCollectionPage - * @param id URL of self - * @param totalItems Number of total items - * @param orderedItems Items - * @param partOf URL of base - * @param prev URL of prev page (optional) - * @param next URL of next page (optional) - */ -export default function ( - id: string, - totalItems: any, - orderedItems: any, - partOf: string, - prev?: string, - next?: string, -) { - const page = { - id, - partOf, - type: "OrderedCollectionPage", - totalItems, - orderedItems, - } as any; - - if (prev) page.prev = prev; - if (next) page.next = next; - - return page; -} diff --git a/packages/backend/src/remote/activitypub/renderer/ordered-collection.ts b/packages/backend/src/remote/activitypub/renderer/ordered-collection.ts deleted file mode 100644 index b975399b68..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/ordered-collection.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Render OrderedCollection - * @param id URL of self - * @param totalItems Total number of items - * @param first URL of first page (optional) - * @param last URL of last page (optional) - * @param orderedItems attached objects (optional) - */ -export default function ( - id: string | null, - totalItems: any, - first?: string, - last?: string, - orderedItems?: Record<string, unknown>[], -): { - id: string | null; - type: "OrderedCollection"; - totalItems: any; - first?: string; - last?: string; - orderedItems?: Record<string, unknown>[]; -} { - const page: any = { - id, - type: "OrderedCollection", - totalItems, - }; - - if (first) page.first = first; - if (last) page.last = last; - if (orderedItems) page.orderedItems = orderedItems; - - return page; -} diff --git a/packages/backend/src/remote/activitypub/renderer/person.ts b/packages/backend/src/remote/activitypub/renderer/person.ts deleted file mode 100644 index 1122a3a279..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/person.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { URL } from "node:url"; -import * as mfm from "mfm-js"; -import config from "@/config/index.js"; -import type { ILocalUser } from "@/models/entities/user.js"; -import { DriveFiles, UserProfiles } from "@/models/index.js"; -import { getUserKeypair } from "@/misc/keypair-store.js"; -import { toHtml } from "../../../mfm/to-html.js"; -import renderImage from "./image.js"; -import renderKey from "./key.js"; -import { getEmojis } from "./note.js"; -import renderEmoji from "./emoji.js"; -import renderHashtag from "./hashtag.js"; -import type { IIdentifier } from "../models/identifier.js"; - -export async function renderPerson(user: ILocalUser) { - const id = `${config.url}/users/${user.id}`; - const isSystem = !!user.username.match(/\./); - - const [avatar, banner, profile] = await Promise.all([ - user.avatarId - ? DriveFiles.findOneBy({ id: user.avatarId }) - : Promise.resolve(undefined), - user.bannerId - ? DriveFiles.findOneBy({ id: user.bannerId }) - : Promise.resolve(undefined), - UserProfiles.findOneByOrFail({ userId: user.id }), - ]); - - const attachment: { - type: "PropertyValue"; - name: string; - value: string; - identifier?: IIdentifier; - }[] = []; - - if (profile.fields) { - for (const field of profile.fields) { - attachment.push({ - type: "PropertyValue", - name: field.name, - value: field.value?.match(/^https?:/) - ? `<a href="${ - new URL(field.value).href - }" rel="me nofollow noopener" target="_blank">${ - new URL(field.value).href - }</a>` - : field.value, - }); - } - } - - const emojis = await getEmojis(user.emojis); - const apemojis = emojis.map((emoji) => renderEmoji(emoji)); - - const hashtagTags = (user.tags || []).map((tag) => renderHashtag(tag)); - - const tag = [...apemojis, ...hashtagTags]; - - const keypair = await getUserKeypair(user.id); - - const person = { - type: isSystem ? "Application" : user.isBot ? "Service" : "Person", - id, - inbox: `${id}/inbox`, - outbox: `${id}/outbox`, - followers: `${id}/followers`, - following: `${id}/following`, - featured: `${id}/collections/featured`, - sharedInbox: `${config.url}/inbox`, - endpoints: { sharedInbox: `${config.url}/inbox` }, - url: `${config.url}/@${user.username}`, - preferredUsername: user.username, - name: user.name, - summary: profile.description - ? toHtml(mfm.parse(profile.description)) - : null, - icon: avatar ? renderImage(avatar) : null, - image: banner ? renderImage(banner) : null, - tag, - manuallyApprovesFollowers: user.isLocked, - discoverable: !!user.isExplorable, - publicKey: renderKey(user, keypair, "#main-key"), - isCat: user.isCat, - attachment: attachment.length ? attachment : undefined, - } as any; - - if (user.movedToUri) { - person.movedTo = user.movedToUri; - } - - if (user.alsoKnownAs) { - person.alsoKnownAs = user.alsoKnownAs; - } - - if (profile.birthday) { - person["vcard:bday"] = profile.birthday; - } - - if (profile.location) { - person["vcard:Address"] = profile.location; - } - - return person; -} diff --git a/packages/backend/src/remote/activitypub/renderer/question.ts b/packages/backend/src/remote/activitypub/renderer/question.ts deleted file mode 100644 index cb89aa7583..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/question.ts +++ /dev/null @@ -1,27 +0,0 @@ -import config from "@/config/index.js"; -import type { User } from "@/models/entities/user.js"; -import type { Note } from "@/models/entities/note.js"; -import type { Poll } from "@/models/entities/poll.js"; - -export default async function renderQuestion( - user: { id: User["id"] }, - note: Note, - poll: Poll, -) { - const question = { - type: "Question", - id: `${config.url}/questions/${note.id}`, - actor: `${config.url}/users/${user.id}`, - content: note.text || "", - [poll.multiple ? "anyOf" : "oneOf"]: poll.choices.map((text, i) => ({ - name: text, - _misskey_votes: poll.votes[i], - replies: { - type: "Collection", - totalItems: poll.votes[i], - }, - })), - }; - - return question; -} diff --git a/packages/backend/src/remote/activitypub/renderer/read.ts b/packages/backend/src/remote/activitypub/renderer/read.ts deleted file mode 100644 index 212e7e8ddf..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/read.ts +++ /dev/null @@ -1,12 +0,0 @@ -import config from "@/config/index.js"; -import type { User } from "@/models/entities/user.js"; -import type { MessagingMessage } from "@/models/entities/messaging-message.js"; - -export const renderReadActivity = ( - user: { id: User["id"] }, - message: MessagingMessage, -) => ({ - type: "Read", - actor: `${config.url}/users/${user.id}`, - object: message.uri, -}); diff --git a/packages/backend/src/remote/activitypub/renderer/reject.ts b/packages/backend/src/remote/activitypub/renderer/reject.ts deleted file mode 100644 index 7ac4452411..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/reject.ts +++ /dev/null @@ -1,8 +0,0 @@ -import config from "@/config/index.js"; -import type { User } from "@/models/entities/user.js"; - -export default (object: any, user: { id: User["id"] }) => ({ - type: "Reject", - actor: `${config.url}/users/${user.id}`, - object, -}); diff --git a/packages/backend/src/remote/activitypub/renderer/remove.ts b/packages/backend/src/remote/activitypub/renderer/remove.ts deleted file mode 100644 index e3b3fef856..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/remove.ts +++ /dev/null @@ -1,9 +0,0 @@ -import config from "@/config/index.js"; -import type { User } from "@/models/entities/user.js"; - -export default (user: { id: User["id"] }, target: any, object: any) => ({ - type: "Remove", - actor: `${config.url}/users/${user.id}`, - target, - object, -}); diff --git a/packages/backend/src/remote/activitypub/renderer/tombstone.ts b/packages/backend/src/remote/activitypub/renderer/tombstone.ts deleted file mode 100644 index 5c4003c75a..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/tombstone.ts +++ /dev/null @@ -1,4 +0,0 @@ -export default (id: string) => ({ - id, - type: "Tombstone", -}); diff --git a/packages/backend/src/remote/activitypub/renderer/undo.ts b/packages/backend/src/remote/activitypub/renderer/undo.ts deleted file mode 100644 index 249d643b25..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/undo.ts +++ /dev/null @@ -1,19 +0,0 @@ -import config from "@/config/index.js"; -import type { User } from "@/models/entities/user.js"; -import { ILocalUser } from "@/models/entities/user.js"; - -export default (object: any, user: { id: User["id"] }) => { - if (object == null) return null; - const id = - typeof object.id === "string" && object.id.startsWith(config.url) - ? `${object.id}/undo` - : undefined; - - return { - type: "Undo", - ...(id ? { id } : {}), - actor: `${config.url}/users/${user.id}`, - object, - published: new Date().toISOString(), - }; -}; diff --git a/packages/backend/src/remote/activitypub/renderer/update.ts b/packages/backend/src/remote/activitypub/renderer/update.ts deleted file mode 100644 index 765a52f06d..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/update.ts +++ /dev/null @@ -1,15 +0,0 @@ -import config from "@/config/index.js"; -import type { User } from "@/models/entities/user.js"; - -export default (object: any, user: { id: User["id"] }) => { - const activity = { - id: `${config.url}/users/${user.id}#updates/${new Date().getTime()}`, - actor: `${config.url}/users/${user.id}`, - type: "Update", - to: ["https://www.w3.org/ns/activitystreams#Public"], - object, - published: new Date().toISOString(), - } as any; - - return activity; -}; diff --git a/packages/backend/src/remote/activitypub/renderer/vote.ts b/packages/backend/src/remote/activitypub/renderer/vote.ts deleted file mode 100644 index 21234a112d..0000000000 --- a/packages/backend/src/remote/activitypub/renderer/vote.ts +++ /dev/null @@ -1,29 +0,0 @@ -import config from "@/config/index.js"; -import type { Note } from "@/models/entities/note.js"; -import type { IRemoteUser, User } from "@/models/entities/user.js"; -import type { PollVote } from "@/models/entities/poll-vote.js"; -import type { Poll } from "@/models/entities/poll.js"; - -export default async function renderVote( - user: { id: User["id"] }, - vote: PollVote, - note: Note, - poll: Poll, - pollOwner: IRemoteUser, -): Promise<any> { - return { - id: `${config.url}/users/${user.id}#votes/${vote.id}/activity`, - actor: `${config.url}/users/${user.id}`, - type: "Create", - to: [pollOwner.uri], - published: new Date().toISOString(), - object: { - id: `${config.url}/users/${user.id}#votes/${vote.id}`, - type: "Note", - attributedTo: `${config.url}/users/${user.id}`, - to: [pollOwner.uri], - inReplyTo: note.uri, - name: poll.choices[vote.choice], - }, - }; -} diff --git a/packages/backend/src/remote/activitypub/request.ts b/packages/backend/src/remote/activitypub/request.ts deleted file mode 100644 index ffb3e25a33..0000000000 --- a/packages/backend/src/remote/activitypub/request.ts +++ /dev/null @@ -1,58 +0,0 @@ -import config from "@/config/index.js"; -import { getUserKeypair } from "@/misc/keypair-store.js"; -import type { User } from "@/models/entities/user.js"; -import { getResponse } from "../../misc/fetch.js"; -import { createSignedPost, createSignedGet } from "./ap-request.js"; - -export default async (user: { id: User["id"] }, url: string, object: any) => { - const body = JSON.stringify(object); - - const keypair = await getUserKeypair(user.id); - - const req = createSignedPost({ - key: { - privateKeyPem: keypair.privateKey, - keyId: `${config.url}/users/${user.id}#main-key`, - }, - url, - body, - additionalHeaders: { - "User-Agent": config.userAgent, - }, - }); - - await getResponse({ - url, - method: req.request.method, - headers: req.request.headers, - body, - }); -}; - -/** - * Get AP object with http-signature - * @param user http-signature user - * @param url URL to fetch - */ -export async function signedGet(url: string, user: { id: User["id"] }) { - const keypair = await getUserKeypair(user.id); - - const req = createSignedGet({ - key: { - privateKeyPem: keypair.privateKey, - keyId: `${config.url}/users/${user.id}#main-key`, - }, - url, - additionalHeaders: { - "User-Agent": config.userAgent, - }, - }); - - const res = await getResponse({ - url, - method: req.request.method, - headers: req.request.headers, - }); - - return await res.json(); -} diff --git a/packages/backend/src/remote/activitypub/resolver.ts b/packages/backend/src/remote/activitypub/resolver.ts deleted file mode 100644 index 0547927609..0000000000 --- a/packages/backend/src/remote/activitypub/resolver.ts +++ /dev/null @@ -1,169 +0,0 @@ -import config from "@/config/index.js"; -import { getJson } from "@/misc/fetch.js"; -import type { ILocalUser } from "@/models/entities/user.js"; -import { getInstanceActor } from "@/services/instance-actor.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { extractDbHost, isSelfHost } from "@/misc/convert-host.js"; -import { signedGet } from "./request.js"; -import type { IObject, ICollection, IOrderedCollection } from "./type.js"; -import { isCollectionOrOrderedCollection, getApId } from "./type.js"; -import { - FollowRequests, - Notes, - NoteReactions, - Polls, - Users, -} from "@/models/index.js"; -import { parseUri } from "./db-resolver.js"; -import renderNote from "@/remote/activitypub/renderer/note.js"; -import { renderLike } from "@/remote/activitypub/renderer/like.js"; -import { renderPerson } from "@/remote/activitypub/renderer/person.js"; -import renderQuestion from "@/remote/activitypub/renderer/question.js"; -import renderCreate from "@/remote/activitypub/renderer/create.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import renderFollow from "@/remote/activitypub/renderer/follow.js"; -import { shouldBlockInstance } from "@/misc/should-block-instance.js"; - -export default class Resolver { - private history: Set<string>; - private user?: ILocalUser; - private recursionLimit?: number; - - constructor(recursionLimit = 100) { - this.history = new Set(); - this.recursionLimit = recursionLimit; - } - - public getHistory(): string[] { - return Array.from(this.history); - } - - public async resolveCollection( - value: string | IObject, - ): Promise<ICollection | IOrderedCollection> { - const collection = await this.resolve(value); - - if (isCollectionOrOrderedCollection(collection)) { - return collection; - } else { - throw new Error(`unrecognized collection type: ${collection.type}`); - } - } - - public async resolve(value: string | IObject): Promise<IObject> { - if (value == null) { - throw new Error("resolvee is null (or undefined)"); - } - - if (typeof value !== "string") { - if (typeof value.id !== "undefined") { - const host = extractDbHost(getApId(value)); - if (await shouldBlockInstance(host)) { - throw new Error("instance is blocked"); - } - } - return value; - } - - if (value.includes("#")) { - // URLs with fragment parts cannot be resolved correctly because - // the fragment part does not get transmitted over HTTP(S). - // Avoid strange behaviour by not trying to resolve these at all. - throw new Error(`cannot resolve URL with fragment: ${value}`); - } - - if (this.history.has(value)) { - throw new Error("cannot resolve already resolved one"); - } - if (this.recursionLimit && this.history.size > this.recursionLimit) { - throw new Error("hit recursion limit"); - } - this.history.add(value); - - const host = extractDbHost(value); - if (isSelfHost(host)) { - return await this.resolveLocal(value); - } - - const meta = await fetchMeta(); - if (await shouldBlockInstance(host, meta)) { - throw new Error("Instance is blocked"); - } - - if ( - meta.privateMode && - config.host !== host && - !meta.allowedHosts.includes(host) - ) { - throw new Error("Instance is not allowed"); - } - - if (!this.user) { - this.user = await getInstanceActor(); - } - - const object = ( - this.user - ? await signedGet(value, this.user) - : await getJson(value, "application/activity+json, application/ld+json") - ) as IObject; - - if ( - object == null || - (Array.isArray(object["@context"]) - ? !(object["@context"] as unknown[]).includes( - "https://www.w3.org/ns/activitystreams", - ) - : object["@context"] !== "https://www.w3.org/ns/activitystreams") - ) { - throw new Error("invalid response"); - } - - return object; - } - - private resolveLocal(url: string): Promise<IObject> { - const parsed = parseUri(url); - if (!parsed.local) throw new Error("resolveLocal: not local"); - - switch (parsed.type) { - case "notes": - return Notes.findOneByOrFail({ id: parsed.id }).then((note) => { - if (parsed.rest === "activity") { - // this refers to the create activity and not the note itself - return renderActivity(renderCreate(renderNote(note))); - } else { - return renderNote(note); - } - }); - case "users": - return Users.findOneByOrFail({ id: parsed.id }).then((user) => - renderPerson(user as ILocalUser), - ); - case "questions": - // Polls are indexed by the note they are attached to. - return Promise.all([ - Notes.findOneByOrFail({ id: parsed.id }), - Polls.findOneByOrFail({ noteId: parsed.id }), - ]).then(([note, poll]) => - renderQuestion({ id: note.userId }, note, poll), - ); - case "likes": - return NoteReactions.findOneByOrFail({ id: parsed.id }).then( - (reaction) => renderActivity(renderLike(reaction, { uri: null })), - ); - case "follows": - // rest should be <followee id> - if (parsed.rest == null || !/^\w+$/.test(parsed.rest)) - throw new Error("resolveLocal: invalid follow URI"); - - return Promise.all( - [parsed.id, parsed.rest].map((id) => Users.findOneByOrFail({ id })), - ).then(([follower, followee]) => - renderActivity(renderFollow(follower, followee, url)), - ); - default: - throw new Error(`resolveLocal: type ${type} unhandled`); - } - } -} diff --git a/packages/backend/src/remote/activitypub/type.ts b/packages/backend/src/remote/activitypub/type.ts deleted file mode 100644 index b0bdb0a8b4..0000000000 --- a/packages/backend/src/remote/activitypub/type.ts +++ /dev/null @@ -1,354 +0,0 @@ -export type obj = { [x: string]: any }; -export type ApObject = IObject | string | (IObject | string)[]; - -export interface IObject { - "@context": string | string[] | obj | obj[]; - type: string | string[]; - id?: string; - summary?: string; - published?: string; - cc?: ApObject; - to?: ApObject; - attributedTo: ApObject; - attachment?: any[]; - inReplyTo?: any; - replies?: ICollection; - content?: string; - name?: string; - startTime?: Date; - endTime?: Date; - icon?: any; - image?: any; - url?: ApObject; - href?: string; - tag?: IObject | IObject[]; - sensitive?: boolean; -} - -/** - * Get array of ActivityStreams Objects id - */ -export function getApIds(value: ApObject | undefined): string[] { - if (value == null) return []; - const array = Array.isArray(value) ? value : [value]; - return array.map((x) => getApId(x)); -} - -/** - * Get first ActivityStreams Object id - */ -export function getOneApId(value: ApObject): string { - const firstOne = Array.isArray(value) ? value[0] : value; - return getApId(firstOne); -} - -/** - * Get ActivityStreams Object id - */ -export function getApId(value: string | IObject): string { - if (typeof value === "string") return value; - if (typeof value.id === "string") return value.id; - throw new Error("cannot detemine id"); -} - -/** - * Get ActivityStreams Object type - */ -export function getApType(value: IObject): string { - if (typeof value.type === "string") return value.type; - if (Array.isArray(value.type) && typeof value.type[0] === "string") - return value.type[0]; - throw new Error("cannot detect type"); -} - -export function getOneApHrefNullable( - value: ApObject | undefined, -): string | undefined { - const firstOne = Array.isArray(value) ? value[0] : value; - return getApHrefNullable(firstOne); -} - -export function getApHrefNullable( - value: string | IObject | undefined, -): string | undefined { - if (typeof value === "string") return value; - if (typeof value?.href === "string") return value.href; - return undefined; -} - -export interface IActivity extends IObject { - //type: 'Activity'; - actor: IObject | string; - object: IObject | string; - target?: IObject | string; - /** LD-Signature */ - signature?: { - type: string; - created: Date; - creator: string; - domain?: string; - nonce?: string; - signatureValue: string; - }; -} - -export interface ICollection extends IObject { - type: "Collection"; - totalItems: number; - items: ApObject; -} - -export interface IOrderedCollection extends IObject { - type: "OrderedCollection"; - totalItems: number; - orderedItems: ApObject; -} - -export const validPost = [ - "Note", - "Question", - "Article", - "Audio", - "Document", - "Image", - "Page", - "Video", - "Event", -]; - -export const isPost = (object: IObject): object is IPost => - validPost.includes(getApType(object)); - -export interface IPost extends IObject { - type: - | "Note" - | "Question" - | "Article" - | "Audio" - | "Document" - | "Image" - | "Page" - | "Video" - | "Event"; - source?: { - content: string; - mediaType: string; - }; - _misskey_quote?: string; - quoteUrl?: string; - quoteUri?: string; - _misskey_talk: boolean; -} - -export interface IQuestion extends IObject { - type: "Note" | "Question"; - source?: { - content: string; - mediaType: string; - }; - _misskey_quote?: string; - quoteUrl?: string; - oneOf?: IQuestionChoice[]; - anyOf?: IQuestionChoice[]; - endTime?: Date; - closed?: Date; -} - -export const isQuestion = (object: IObject): object is IQuestion => - getApType(object) === "Note" || getApType(object) === "Question"; - -interface IQuestionChoice { - name?: string; - replies?: ICollection; - _misskey_votes?: number; -} -export interface ITombstone extends IObject { - type: "Tombstone"; - formerType?: string; - deleted?: Date; -} - -export const isTombstone = (object: IObject): object is ITombstone => - getApType(object) === "Tombstone"; - -export const validActor = [ - "Person", - "Service", - "Group", - "Organization", - "Application", -]; - -export const isActor = (object: IObject): object is IActor => - validActor.includes(getApType(object)); - -export interface IActor extends IObject { - type: "Person" | "Service" | "Organization" | "Group" | "Application"; - name?: string; - preferredUsername?: string; - manuallyApprovesFollowers?: boolean; - movedTo?: string; - alsoKnownAs?: string[]; - discoverable?: boolean; - inbox: string; - sharedInbox?: string; // backward compatibility.. ig - publicKey?: { - id: string; - publicKeyPem: string; - }; - followers?: string | ICollection | IOrderedCollection; - following?: string | ICollection | IOrderedCollection; - featured?: string | IOrderedCollection; - outbox: string | IOrderedCollection; - endpoints?: { - sharedInbox?: string; - }; - "vcard:bday"?: string; - "vcard:Address"?: string; -} - -export const isCollection = (object: IObject): object is ICollection => - getApType(object) === "Collection"; - -export const isOrderedCollection = ( - object: IObject, -): object is IOrderedCollection => getApType(object) === "OrderedCollection"; - -export const isCollectionOrOrderedCollection = ( - object: IObject, -): object is ICollection | IOrderedCollection => - isCollection(object) || isOrderedCollection(object); - -export interface IApPropertyValue extends IObject { - type: "PropertyValue"; - identifier: IApPropertyValue; - name: string; - value: string; -} - -export const isPropertyValue = (object: IObject): object is IApPropertyValue => - object && - getApType(object) === "PropertyValue" && - typeof object.name === "string" && - typeof (object as any).value === "string"; - -export interface IApMention extends IObject { - type: "Mention"; - href: string; -} - -export const isMention = (object: IObject): object is IApMention => - getApType(object) === "Mention" && typeof object.href === "string"; - -export interface IApHashtag extends IObject { - type: "Hashtag"; - name: string; -} - -export const isHashtag = (object: IObject): object is IApHashtag => - getApType(object) === "Hashtag" && typeof object.name === "string"; - -export interface IApEmoji extends IObject { - type: "Emoji"; - updated: Date; -} - -export const isEmoji = (object: IObject): object is IApEmoji => - getApType(object) === "Emoji" && - !Array.isArray(object.icon) && - object.icon.url != null; - -export interface ICreate extends IActivity { - type: "Create"; -} - -export interface IDelete extends IActivity { - type: "Delete"; -} - -export interface IUpdate extends IActivity { - type: "Update"; -} - -export interface IRead extends IActivity { - type: "Read"; -} - -export interface IUndo extends IActivity { - type: "Undo"; -} - -export interface IFollow extends IActivity { - type: "Follow"; -} - -export interface IAccept extends IActivity { - type: "Accept"; -} - -export interface IReject extends IActivity { - type: "Reject"; -} - -export interface IAdd extends IActivity { - type: "Add"; -} - -export interface IRemove extends IActivity { - type: "Remove"; -} - -export interface ILike extends IActivity { - type: "Like" | "EmojiReaction" | "EmojiReact"; - _misskey_reaction?: string; -} - -export interface IAnnounce extends IActivity { - type: "Announce"; -} - -export interface IBlock extends IActivity { - type: "Block"; -} - -export interface IFlag extends IActivity { - type: "Flag"; -} - -export interface IMove extends IActivity { - type: "Move"; - target: IObject | string; -} - -export const isCreate = (object: IObject): object is ICreate => - getApType(object) === "Create"; -export const isDelete = (object: IObject): object is IDelete => - getApType(object) === "Delete"; -export const isUpdate = (object: IObject): object is IUpdate => - getApType(object) === "Update"; -export const isRead = (object: IObject): object is IRead => - getApType(object) === "Read"; -export const isUndo = (object: IObject): object is IUndo => - getApType(object) === "Undo"; -export const isFollow = (object: IObject): object is IFollow => - getApType(object) === "Follow"; -export const isAccept = (object: IObject): object is IAccept => - getApType(object) === "Accept"; -export const isReject = (object: IObject): object is IReject => - getApType(object) === "Reject"; -export const isAdd = (object: IObject): object is IAdd => - getApType(object) === "Add"; -export const isRemove = (object: IObject): object is IRemove => - getApType(object) === "Remove"; -export const isLike = (object: IObject): object is ILike => - getApType(object) === "Like" || - getApType(object) === "EmojiReaction" || - getApType(object) === "EmojiReact"; -export const isAnnounce = (object: IObject): object is IAnnounce => - getApType(object) === "Announce"; -export const isBlock = (object: IObject): object is IBlock => - getApType(object) === "Block"; -export const isFlag = (object: IObject): object is IFlag => - getApType(object) === "Flag"; -export const isMove = (object: IObject): object is IMove => - getApType(object) === "Move"; diff --git a/packages/backend/src/remote/logger.ts b/packages/backend/src/remote/logger.ts deleted file mode 100644 index b6bc5bf6dd..0000000000 --- a/packages/backend/src/remote/logger.ts +++ /dev/null @@ -1,3 +0,0 @@ -import Logger from "@/services/logger.js"; - -export const remoteLogger = new Logger("remote", "cyan"); diff --git a/packages/backend/src/remote/resolve-user.ts b/packages/backend/src/remote/resolve-user.ts deleted file mode 100644 index a6c1e399a5..0000000000 --- a/packages/backend/src/remote/resolve-user.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { URL } from "node:url"; -import chalk from "chalk"; -import { IsNull } from "typeorm"; -import config from "@/config/index.js"; -import type { User, IRemoteUser } from "@/models/entities/user.js"; -import { Users } from "@/models/index.js"; -import { toPuny } from "@/misc/convert-host.js"; -import webFinger from "./webfinger.js"; -import { createPerson, updatePerson } from "./activitypub/models/person.js"; -import { remoteLogger } from "./logger.js"; - -const logger = remoteLogger.createSubLogger("resolve-user"); - -export async function resolveUser( - username: string, - host: string | null, -): Promise<User> { - const usernameLower = username.toLowerCase(); - - if (host == null) { - logger.info(`return local user: ${usernameLower}`); - return await Users.findOneBy({ usernameLower, host: IsNull() }).then( - (u) => { - if (u == null) { - throw new Error("user not found"); - } else { - return u; - } - }, - ); - } - - host = toPuny(host); - - if (config.host === host) { - logger.info(`return local user: ${usernameLower}`); - return await Users.findOneBy({ usernameLower, host: IsNull() }).then( - (u) => { - if (u == null) { - throw new Error("user not found"); - } else { - return u; - } - }, - ); - } - - const user = (await Users.findOneBy({ - usernameLower, - host, - })) as IRemoteUser | null; - - const acctLower = `${usernameLower}@${host}`; - - if (user == null) { - const self = await resolveSelf(acctLower); - - logger.succ(`return new remote user: ${chalk.magenta(acctLower)}`); - return await createPerson(self.href); - } - - // If user information is out of date, return it by starting over from WebFilger - if ( - user.lastFetchedAt == null || - Date.now() - user.lastFetchedAt.getTime() > 1000 * 60 * 60 * 24 - ) { - // Prevent multiple attempts to connect to unconnected instances, update before each attempt to prevent subsequent similar attempts - await Users.update(user.id, { - lastFetchedAt: new Date(), - }); - - logger.info(`try resync: ${acctLower}`); - const self = await resolveSelf(acctLower); - - if (user.uri !== self.href) { - // if uri mismatch, Fix (user@host <=> AP's Person id(IRemoteUser.uri)) mapping. - logger.info(`uri missmatch: ${acctLower}`); - logger.info( - `recovery missmatch uri for (username=${username}, host=${host}) from ${user.uri} to ${self.href}`, - ); - - // validate uri - const uri = new URL(self.href); - if (uri.hostname !== host) { - throw new Error("Invalid uri"); - } - - await Users.update( - { - usernameLower, - host: host, - }, - { - uri: self.href, - }, - ); - } else { - logger.info(`uri is fine: ${acctLower}`); - } - - await updatePerson(self.href); - - logger.info(`return resynced remote user: ${acctLower}`); - return await Users.findOneBy({ uri: self.href }).then((u) => { - if (u == null) { - throw new Error("user not found"); - } else { - return u; - } - }); - } - - logger.info(`return existing remote user: ${acctLower}`); - return user; -} - -async function resolveSelf(acctLower: string) { - logger.info(`WebFinger for ${chalk.yellow(acctLower)}`); - const finger = await webFinger(acctLower).catch((e) => { - logger.error( - `Failed to WebFinger for ${chalk.yellow(acctLower)}: ${ - e.statusCode || e.message - }`, - ); - throw new Error( - `Failed to WebFinger for ${acctLower}: ${e.statusCode || e.message}`, - ); - }); - const self = finger.links.find( - (link) => link.rel != null && link.rel.toLowerCase() === "self", - ); - if (!self) { - logger.error( - `Failed to WebFinger for ${chalk.yellow(acctLower)}: self link not found`, - ); - throw new Error("self link not found"); - } - return self; -} diff --git a/packages/backend/src/remote/webfinger.ts b/packages/backend/src/remote/webfinger.ts deleted file mode 100644 index 1e929c8ff1..0000000000 --- a/packages/backend/src/remote/webfinger.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { URL } from "node:url"; -import { getJson } from "@/misc/fetch.js"; -import { query as urlQuery } from "@/prelude/url.js"; - -type ILink = { - href: string; - rel?: string; -}; - -type IWebFinger = { - links: ILink[]; - subject: string; -}; - -export default async function (query: string): Promise<IWebFinger> { - const url = genUrl(query); - - return (await getJson( - url, - "application/jrd+json, application/json", - )) as IWebFinger; -} - -function genUrl(query: string) { - if (query.match(/^https?:\/\//)) { - const u = new URL(query); - return `${u.protocol}//${u.hostname}/.well-known/webfinger?${urlQuery({ - resource: query, - })}`; - } - - const m = query.match(/^([^@]+)@(.*)/); - if (m) { - const hostname = m[2]; - return `https://${hostname}/.well-known/webfinger?${urlQuery({ - resource: `acct:${query}`, - })}`; - } - - throw new Error(`Invalid query (${query})`); -} diff --git a/packages/backend/src/server/activitypub.ts b/packages/backend/src/server/activitypub.ts deleted file mode 100644 index 29ac726efc..0000000000 --- a/packages/backend/src/server/activitypub.ts +++ /dev/null @@ -1,368 +0,0 @@ -import Router from "@koa/router"; -import json from "koa-json-body"; -import httpSignature from "@peertube/http-signature"; - -import { In, IsNull, Not } from "typeorm"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import renderNote from "@/remote/activitypub/renderer/note.js"; -import renderKey from "@/remote/activitypub/renderer/key.js"; -import { renderPerson } from "@/remote/activitypub/renderer/person.js"; -import renderEmoji from "@/remote/activitypub/renderer/emoji.js"; -import { inbox as processInbox } from "@/queue/index.js"; -import { isSelfHost, toPuny } from "@/misc/convert-host.js"; -import { Notes, Users, Emojis, NoteReactions } from "@/models/index.js"; -import type { ILocalUser, User } from "@/models/entities/user.js"; -import { renderLike } from "@/remote/activitypub/renderer/like.js"; -import { getUserKeypair } from "@/misc/keypair-store.js"; -import { checkFetch, hasSignature } from "@/remote/activitypub/check-fetch.js"; -import { getInstanceActor } from "@/services/instance-actor.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import renderFollow from "@/remote/activitypub/renderer/follow.js"; -import Featured from "./activitypub/featured.js"; -import Following from "./activitypub/following.js"; -import Followers from "./activitypub/followers.js"; -import Outbox, { packActivity } from "./activitypub/outbox.js"; - -// Init router -const router = new Router(); - -//#region Routing - -function inbox(ctx: Router.RouterContext) { - let signature; - - try { - signature = httpSignature.parseRequest(ctx.req, { headers: [] }); - } catch (e) { - ctx.status = 401; - return; - } - - processInbox(ctx.request.body, signature); - - ctx.status = 202; -} - -const ACTIVITY_JSON = "application/activity+json; charset=utf-8"; -const LD_JSON = - 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"; charset=utf-8'; - -function isActivityPubReq(ctx: Router.RouterContext) { - ctx.response.vary("Accept"); - const accepted = ctx.accepts("html", ACTIVITY_JSON, LD_JSON); - return typeof accepted === "string" && !accepted.match(/html/); -} - -export function setResponseType(ctx: Router.RouterContext) { - const accept = ctx.accepts(ACTIVITY_JSON, LD_JSON); - if (accept === LD_JSON) { - ctx.response.type = LD_JSON; - } else { - ctx.response.type = ACTIVITY_JSON; - } -} - -// inbox -router.post("/inbox", json(), inbox); -router.post("/users/:user/inbox", json(), inbox); - -// note -router.get("/notes/:note", async (ctx, next) => { - if (!isActivityPubReq(ctx)) return await next(); - - const verify = await checkFetch(ctx.req); - if (verify !== 200) { - ctx.status = verify; - return; - } - - const note = await Notes.findOneBy({ - id: ctx.params.note, - visibility: In(["public" as const, "home" as const]), - localOnly: false, - }); - - if (note == null) { - ctx.status = 404; - return; - } - - // redirect if remote - if (note.userHost !== null) { - if (note.uri == null || isSelfHost(note.userHost)) { - ctx.status = 500; - return; - } - ctx.redirect(note.uri); - return; - } - - ctx.body = renderActivity(await renderNote(note, false)); - - const meta = await fetchMeta(); - if (meta.secureMode || meta.privateMode) { - ctx.set("Cache-Control", "private, max-age=0, must-revalidate"); - } else { - ctx.set("Cache-Control", "public, max-age=180"); - } - setResponseType(ctx); -}); - -// note activity -router.get("/notes/:note/activity", async (ctx) => { - const verify = await checkFetch(ctx.req); - if (verify !== 200) { - ctx.status = verify; - return; - } - - const note = await Notes.findOneBy({ - id: ctx.params.note, - userHost: IsNull(), - visibility: In(["public" as const, "home" as const]), - localOnly: false, - }); - - if (note == null) { - ctx.status = 404; - return; - } - - ctx.body = renderActivity(await packActivity(note)); - const meta = await fetchMeta(); - if (meta.secureMode || meta.privateMode) { - ctx.set("Cache-Control", "private, max-age=0, must-revalidate"); - } else { - ctx.set("Cache-Control", "public, max-age=180"); - } - setResponseType(ctx); -}); - -// outbox -router.get("/users/:user/outbox", Outbox); - -// followers -router.get("/users/:user/followers", Followers); - -// following -router.get("/users/:user/following", Following); - -// featured -router.get("/users/:user/collections/featured", Featured); - -// publickey -router.get("/users/:user/publickey", async (ctx) => { - const instanceActor = await getInstanceActor(); - if (ctx.params.user === instanceActor.id) { - ctx.body = renderActivity( - renderKey(instanceActor, await getUserKeypair(instanceActor.id)), - ); - ctx.set("Cache-Control", "public, max-age=180"); - setResponseType(ctx); - return; - } - - const verify = await checkFetch(ctx.req); - if (verify !== 200) { - ctx.status = verify; - return; - } - - const userId = ctx.params.user; - - const user = await Users.findOneBy({ - id: userId, - host: IsNull(), - }); - - if (user == null) { - ctx.status = 404; - return; - } - - const keypair = await getUserKeypair(user.id); - - if (Users.isLocalUser(user)) { - ctx.body = renderActivity(renderKey(user, keypair)); - const meta = await fetchMeta(); - if (meta.secureMode || meta.privateMode) { - ctx.set("Cache-Control", "private, max-age=0, must-revalidate"); - } else { - ctx.set("Cache-Control", "public, max-age=180"); - } - setResponseType(ctx); - } else { - ctx.status = 400; - } -}); - -// user -async function userInfo(ctx: Router.RouterContext, user: User | null) { - if (user == null) { - ctx.status = 404; - return; - } - - ctx.body = renderActivity(await renderPerson(user as ILocalUser)); - const meta = await fetchMeta(); - if (meta.secureMode || meta.privateMode) { - ctx.set("Cache-Control", "private, max-age=0, must-revalidate"); - } else { - ctx.set("Cache-Control", "public, max-age=180"); - } - setResponseType(ctx); -} - -router.get("/users/:user", async (ctx, next) => { - if (!isActivityPubReq(ctx)) return await next(); - - const instanceActor = await getInstanceActor(); - if (ctx.params.user === instanceActor.id) { - await userInfo(ctx, instanceActor); - return; - } - - const verify = await checkFetch(ctx.req); - if (verify !== 200) { - ctx.status = verify; - return; - } - - const userId = ctx.params.user; - - const user = await Users.findOneBy({ - id: userId, - host: IsNull(), - isSuspended: false, - }); - - await userInfo(ctx, user); -}); - -router.get("/@:user", async (ctx, next) => { - if (!isActivityPubReq(ctx)) return await next(); - - if (ctx.params.user === "instance.actor") { - const instanceActor = await getInstanceActor(); - await userInfo(ctx, instanceActor); - return; - } - - const verify = await checkFetch(ctx.req); - if (verify !== 200) { - ctx.status = verify; - return; - } - - const user = await Users.findOneBy({ - usernameLower: ctx.params.user.toLowerCase(), - host: IsNull(), - isSuspended: false, - }); - - await userInfo(ctx, user); -}); - -router.get("/actor", async (ctx, next) => { - const instanceActor = await getInstanceActor(); - await userInfo(ctx, instanceActor); -}); -//#endregion - -// emoji -router.get("/emojis/:emoji", async (ctx) => { - const verify = await checkFetch(ctx.req); - if (verify !== 200) { - ctx.status = verify; - return; - } - - const emoji = await Emojis.findOneBy({ - host: IsNull(), - name: ctx.params.emoji, - }); - - if (emoji == null) { - ctx.status = 404; - return; - } - - ctx.body = renderActivity(await renderEmoji(emoji)); - const meta = await fetchMeta(); - if (meta.secureMode || meta.privateMode) { - ctx.set("Cache-Control", "private, max-age=0, must-revalidate"); - } else { - ctx.set("Cache-Control", "public, max-age=180"); - } - setResponseType(ctx); -}); - -// like -router.get("/likes/:like", async (ctx) => { - const verify = await checkFetch(ctx.req); - if (verify !== 200) { - ctx.status = verify; - return; - } - - const reaction = await NoteReactions.findOneBy({ id: ctx.params.like }); - - if (reaction == null) { - ctx.status = 404; - return; - } - - const note = await Notes.findOneBy({ id: reaction.noteId }); - - if (note == null) { - ctx.status = 404; - return; - } - - ctx.body = renderActivity(await renderLike(reaction, note)); - const meta = await fetchMeta(); - if (meta.secureMode || meta.privateMode) { - ctx.set("Cache-Control", "private, max-age=0, must-revalidate"); - } else { - ctx.set("Cache-Control", "public, max-age=180"); - } - setResponseType(ctx); -}); - -// follow -router.get("/follows/:follower/:followee", async (ctx) => { - const verify = await checkFetch(ctx.req); - if (verify !== 200) { - ctx.status = verify; - return; - } - // This may be used before the follow is completed, so we do not - // check if the following exists. - - const [follower, followee] = await Promise.all([ - Users.findOneBy({ - id: ctx.params.follower, - host: IsNull(), - }), - Users.findOneBy({ - id: ctx.params.followee, - host: Not(IsNull()), - }), - ]); - - if (follower == null || followee == null) { - ctx.status = 404; - return; - } - - ctx.body = renderActivity(renderFollow(follower, followee)); - const meta = await fetchMeta(); - if (meta.secureMode || meta.privateMode) { - ctx.set("Cache-Control", "private, max-age=0, must-revalidate"); - } else { - ctx.set("Cache-Control", "public, max-age=180"); - } - setResponseType(ctx); -}); - -export default router; diff --git a/packages/backend/src/server/activitypub/featured.ts b/packages/backend/src/server/activitypub/featured.ts deleted file mode 100644 index 82bb19fa12..0000000000 --- a/packages/backend/src/server/activitypub/featured.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { IsNull } from "typeorm"; -import config from "@/config/index.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import renderOrderedCollection from "@/remote/activitypub/renderer/ordered-collection.js"; -import renderNote from "@/remote/activitypub/renderer/note.js"; -import { Users, Notes, UserNotePinings } from "@/models/index.js"; -import { checkFetch } from "@/remote/activitypub/check-fetch.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { setResponseType } from "../activitypub.js"; -import type Router from "@koa/router"; - -export default async (ctx: Router.RouterContext) => { - const verify = await checkFetch(ctx.req); - if (verify !== 200) { - ctx.status = verify; - return; - } - - const userId = ctx.params.user; - - const user = await Users.findOneBy({ - id: userId, - host: IsNull(), - }); - - if (user == null) { - ctx.status = 404; - return; - } - - const pinings = await UserNotePinings.find({ - where: { userId: user.id }, - order: { id: "DESC" }, - }); - - const pinnedNotes = await Promise.all( - pinings.map((pining) => Notes.findOneByOrFail({ id: pining.noteId })), - ); - - const renderedNotes = await Promise.all( - pinnedNotes.map((note) => renderNote(note)), - ); - - const rendered = renderOrderedCollection( - `${config.url}/users/${userId}/collections/featured`, - renderedNotes.length, - undefined, - undefined, - renderedNotes, - ); - - ctx.body = renderActivity(rendered); - - const meta = await fetchMeta(); - if (meta.secureMode || meta.privateMode) { - ctx.set("Cache-Control", "private, max-age=0, must-revalidate"); - } else { - ctx.set("Cache-Control", "public, max-age=180"); - } - setResponseType(ctx); -}; diff --git a/packages/backend/src/server/activitypub/followers.ts b/packages/backend/src/server/activitypub/followers.ts deleted file mode 100644 index 146ca51928..0000000000 --- a/packages/backend/src/server/activitypub/followers.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { IsNull, LessThan } from "typeorm"; -import config from "@/config/index.js"; -import * as url from "@/prelude/url.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import renderOrderedCollection from "@/remote/activitypub/renderer/ordered-collection.js"; -import renderOrderedCollectionPage from "@/remote/activitypub/renderer/ordered-collection-page.js"; -import renderFollowUser from "@/remote/activitypub/renderer/follow-user.js"; -import { Users, Followings, UserProfiles } from "@/models/index.js"; -import type { Following } from "@/models/entities/following.js"; -import { checkFetch } from "@/remote/activitypub/check-fetch.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { setResponseType } from "../activitypub.js"; -import type { FindOptionsWhere } from "typeorm"; -import type Router from "@koa/router"; - -export default async (ctx: Router.RouterContext) => { - const verify = await checkFetch(ctx.req); - if (verify !== 200) { - ctx.status = verify; - return; - } - - const userId = ctx.params.user; - - const cursor = ctx.request.query.cursor; - if (cursor != null && typeof cursor !== "string") { - ctx.status = 400; - return; - } - - const page = ctx.request.query.page === "true"; - - const user = await Users.findOneBy({ - id: userId, - host: IsNull(), - }); - - if (user == null) { - ctx.status = 404; - return; - } - - //#region Check ff visibility - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - if (profile.ffVisibility === "private") { - ctx.status = 403; - ctx.set("Cache-Control", "public, max-age=30"); - return; - } else if (profile.ffVisibility === "followers") { - ctx.status = 403; - ctx.set("Cache-Control", "public, max-age=30"); - return; - } - //#endregion - - const limit = 10; - const partOf = `${config.url}/users/${userId}/followers`; - - if (page) { - const query = { - followeeId: user.id, - } as FindOptionsWhere<Following>; - - // カーソルが指定されている場合 - if (cursor) { - query.id = LessThan(cursor); - } - - // Get followers - const followings = await Followings.find({ - where: query, - take: limit + 1, - order: { id: -1 }, - }); - - // 「次のページ」があるかどうか - const inStock = followings.length === limit + 1; - if (inStock) followings.pop(); - - const renderedFollowers = await Promise.all( - followings.map((following) => renderFollowUser(following.followerId)), - ); - const rendered = renderOrderedCollectionPage( - `${partOf}?${url.query({ - page: "true", - cursor, - })}`, - user.followersCount, - renderedFollowers, - partOf, - undefined, - inStock - ? `${partOf}?${url.query({ - page: "true", - cursor: followings[followings.length - 1].id, - })}` - : undefined, - ); - - ctx.body = renderActivity(rendered); - setResponseType(ctx); - } else { - // index page - const rendered = renderOrderedCollection( - partOf, - user.followersCount, - `${partOf}?page=true`, - ); - ctx.body = renderActivity(rendered); - setResponseType(ctx); - } - const meta = await fetchMeta(); - if (meta.secureMode || meta.privateMode) { - ctx.set("Cache-Control", "private, max-age=0, must-revalidate"); - } else { - ctx.set("Cache-Control", "public, max-age=180"); - } -}; diff --git a/packages/backend/src/server/activitypub/following.ts b/packages/backend/src/server/activitypub/following.ts deleted file mode 100644 index eab513ce64..0000000000 --- a/packages/backend/src/server/activitypub/following.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { LessThan, IsNull } from "typeorm"; -import config from "@/config/index.js"; -import * as url from "@/prelude/url.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import renderOrderedCollection from "@/remote/activitypub/renderer/ordered-collection.js"; -import renderOrderedCollectionPage from "@/remote/activitypub/renderer/ordered-collection-page.js"; -import renderFollowUser from "@/remote/activitypub/renderer/follow-user.js"; -import { Users, Followings, UserProfiles } from "@/models/index.js"; -import type { Following } from "@/models/entities/following.js"; -import { checkFetch } from "@/remote/activitypub/check-fetch.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { setResponseType } from "../activitypub.js"; -import type { FindOptionsWhere } from "typeorm"; -import type Router from "@koa/router"; - -export default async (ctx: Router.RouterContext) => { - const verify = await checkFetch(ctx.req); - if (verify !== 200) { - ctx.status = verify; - return; - } - - const userId = ctx.params.user; - - const cursor = ctx.request.query.cursor; - if (cursor != null && typeof cursor !== "string") { - ctx.status = 400; - return; - } - - const page = ctx.request.query.page === "true"; - - const user = await Users.findOneBy({ - id: userId, - host: IsNull(), - }); - - if (user == null) { - ctx.status = 404; - return; - } - - //#region Check ff visibility - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - if (profile.ffVisibility === "private") { - ctx.status = 403; - ctx.set("Cache-Control", "public, max-age=30"); - return; - } else if (profile.ffVisibility === "followers") { - ctx.status = 403; - ctx.set("Cache-Control", "public, max-age=30"); - return; - } - //#endregion - - const limit = 10; - const partOf = `${config.url}/users/${userId}/following`; - - if (page) { - const query = { - followerId: user.id, - } as FindOptionsWhere<Following>; - - // If a cursor is specified - if (cursor) { - query.id = LessThan(cursor); - } - - // Get followings - const followings = await Followings.find({ - where: query, - take: limit + 1, - order: { id: -1 }, - }); - - // Whether there is a "next page" or not - const inStock = followings.length === limit + 1; - if (inStock) followings.pop(); - - const renderedFollowees = await Promise.all( - followings.map((following) => renderFollowUser(following.followeeId)), - ); - const rendered = renderOrderedCollectionPage( - `${partOf}?${url.query({ - page: "true", - cursor, - })}`, - user.followingCount, - renderedFollowees, - partOf, - undefined, - inStock - ? `${partOf}?${url.query({ - page: "true", - cursor: followings[followings.length - 1].id, - })}` - : undefined, - ); - - ctx.body = renderActivity(rendered); - setResponseType(ctx); - } else { - // index page - const rendered = renderOrderedCollection( - partOf, - user.followingCount, - `${partOf}?page=true`, - ); - ctx.body = renderActivity(rendered); - setResponseType(ctx); - } - const meta = await fetchMeta(); - if (meta.secureMode || meta.privateMode) { - ctx.set("Cache-Control", "private, max-age=0, must-revalidate"); - } else { - ctx.set("Cache-Control", "public, max-age=180"); - } -}; diff --git a/packages/backend/src/server/activitypub/outbox.ts b/packages/backend/src/server/activitypub/outbox.ts deleted file mode 100644 index e0a380ffb6..0000000000 --- a/packages/backend/src/server/activitypub/outbox.ts +++ /dev/null @@ -1,147 +0,0 @@ -import { Brackets, IsNull } from "typeorm"; -import config from "@/config/index.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import renderOrderedCollection from "@/remote/activitypub/renderer/ordered-collection.js"; -import renderOrderedCollectionPage from "@/remote/activitypub/renderer/ordered-collection-page.js"; -import renderNote from "@/remote/activitypub/renderer/note.js"; -import renderCreate from "@/remote/activitypub/renderer/create.js"; -import renderAnnounce from "@/remote/activitypub/renderer/announce.js"; -import { countIf } from "@/prelude/array.js"; -import * as url from "@/prelude/url.js"; -import { Users, Notes } from "@/models/index.js"; -import type { Note } from "@/models/entities/note.js"; -import { checkFetch } from "@/remote/activitypub/check-fetch.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { makePaginationQuery } from "../api/common/make-pagination-query.js"; -import { setResponseType } from "../activitypub.js"; -import type Router from "@koa/router"; - -export default async (ctx: Router.RouterContext) => { - const verify = await checkFetch(ctx.req); - if (verify !== 200) { - ctx.status = verify; - return; - } - - const userId = ctx.params.user; - - const sinceId = ctx.request.query.since_id; - if (sinceId != null && typeof sinceId !== "string") { - ctx.status = 400; - return; - } - - const untilId = ctx.request.query.until_id; - if (untilId != null && typeof untilId !== "string") { - ctx.status = 400; - return; - } - - const page = ctx.request.query.page === "true"; - - if (countIf((x) => x != null, [sinceId, untilId]) > 1) { - ctx.status = 400; - return; - } - - const user = await Users.findOneBy({ - id: userId, - host: IsNull(), - }); - - if (user == null) { - ctx.status = 404; - return; - } - - const limit = 20; - const partOf = `${config.url}/users/${userId}/outbox`; - - if (page) { - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - sinceId, - untilId, - ) - .andWhere("note.userId = :userId", { userId: user.id }) - .andWhere( - new Brackets((qb) => { - qb.where("note.visibility = 'public'").orWhere( - "note.visibility = 'home'", - ); - }), - ) - .andWhere("note.localOnly = FALSE"); - - const notes = await query.take(limit).getMany(); - - if (sinceId) notes.reverse(); - - const activities = await Promise.all( - notes.map((note) => packActivity(note)), - ); - const rendered = renderOrderedCollectionPage( - `${partOf}?${url.query({ - page: "true", - since_id: sinceId, - until_id: untilId, - })}`, - user.notesCount, - activities, - partOf, - notes.length - ? `${partOf}?${url.query({ - page: "true", - since_id: notes[0].id, - })}` - : undefined, - notes.length - ? `${partOf}?${url.query({ - page: "true", - until_id: notes[notes.length - 1].id, - })}` - : undefined, - ); - - ctx.body = renderActivity(rendered); - setResponseType(ctx); - } else { - // index page - const rendered = renderOrderedCollection( - partOf, - user.notesCount, - `${partOf}?page=true`, - `${partOf}?page=true&since_id=000000000000000000000000`, - ); - ctx.body = renderActivity(rendered); - - setResponseType(ctx); - } - const meta = await fetchMeta(); - if (meta.secureMode || meta.privateMode) { - ctx.set("Cache-Control", "private, max-age=0, must-revalidate"); - } else { - ctx.set("Cache-Control", "public, max-age=180"); - } -}; - -/** - * Pack Create<Note> or Announce Activity - * @param note Note - */ -export async function packActivity(note: Note): Promise<any> { - if ( - note.renoteId && - note.text == null && - !note.hasPoll && - (note.fileIds == null || note.fileIds.length === 0) - ) { - const renote = await Notes.findOneByOrFail({ id: note.renoteId }); - return renderAnnounce( - renote.uri ? renote.uri : `${config.url}/notes/${renote.id}`, - note, - ); - } - - return renderCreate(await renderNote(note, false), note); -} diff --git a/packages/backend/src/server/api/2fa.ts b/packages/backend/src/server/api/2fa.ts deleted file mode 100644 index 7318f0f433..0000000000 --- a/packages/backend/src/server/api/2fa.ts +++ /dev/null @@ -1,417 +0,0 @@ -import * as crypto from "node:crypto"; -import * as jsrsasign from "jsrsasign"; -import config from "@/config/index.js"; - -const ECC_PRELUDE = Buffer.from([0x04]); -const NULL_BYTE = Buffer.from([0]); -const PEM_PRELUDE = Buffer.from( - "3059301306072a8648ce3d020106082a8648ce3d030107034200", - "hex", -); - -// Android Safetynet attestations are signed with this cert: -const GSR2 = `-----BEGIN CERTIFICATE----- -MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4G -A1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNp -Z24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1 -MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEG -A1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6ErPL -v4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8 -eoLrvozps6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklq -tTleiDTsvHgMCJiEbKjNS7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzd -C9XZzPnqJworc5HGnRusyMvo4KD0L5CLTfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pa -zq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6CygPCm48CAwEAAaOBnDCB -mTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUm+IH -V2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5n -bG9iYWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG -3lm0mi3f3BmGLjANBgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4Gs -J0/WwbgcQ3izDJr86iw8bmEbTUsp9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO -291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu01yiPqFbQfXf5WRDLenVOavS -ot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG79G+dwfCMNYxd -AfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7 -TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg== ------END CERTIFICATE-----\n`; - -function base64URLDecode(source: string) { - return Buffer.from(source.replace(/\-/g, "+").replace(/_/g, "/"), "base64"); -} - -function getCertSubject(certificate: string) { - const subjectCert = new jsrsasign.X509(); - subjectCert.readCertPEM(certificate); - - const subjectString = subjectCert.getSubjectString(); - const subjectFields = subjectString.slice(1).split("/"); - - const fields = {} as Record<string, string>; - for (const field of subjectFields) { - const eqIndex = field.indexOf("="); - fields[field.substring(0, eqIndex)] = field.substring(eqIndex + 1); - } - - return fields; -} - -function verifyCertificateChain(certificates: string[]) { - let valid = true; - - for (let i = 0; i < certificates.length; i++) { - const Cert = certificates[i]; - const certificate = new jsrsasign.X509(); - certificate.readCertPEM(Cert); - - const CACert = i + 1 >= certificates.length ? Cert : certificates[i + 1]; - - const certStruct = jsrsasign.ASN1HEX.getTLVbyList(certificate.hex!, 0, [0]); - const algorithm = certificate.getSignatureAlgorithmField(); - const signatureHex = certificate.getSignatureValueHex(); - - // Verify against CA - const Signature = new jsrsasign.KJUR.crypto.Signature({ alg: algorithm }); - Signature.init(CACert); - Signature.updateHex(certStruct); - valid = valid && !!Signature.verify(signatureHex); // true if CA signed the certificate - } - - return valid; -} - -function PEMString(pemBuffer: Buffer, type = "CERTIFICATE") { - if (pemBuffer.length === 65 && pemBuffer[0] === 0x04) { - pemBuffer = Buffer.concat([PEM_PRELUDE, pemBuffer], 91); - type = "PUBLIC KEY"; - } - const cert = pemBuffer.toString("base64"); - - const keyParts = []; - const max = Math.ceil(cert.length / 64); - let start = 0; - for (let i = 0; i < max; i++) { - keyParts.push(cert.substring(start, start + 64)); - start += 64; - } - - return `-----BEGIN ${type}-----\n${keyParts.join( - "\n", - )}\n-----END ${type}-----\n`; -} - -export function hash(data: Buffer) { - return crypto.createHash("sha256").update(data).digest(); -} - -export function verifyLogin({ - publicKey, - authenticatorData, - clientDataJSON, - clientData, - signature, - challenge, -}: { - publicKey: Buffer; - authenticatorData: Buffer; - clientDataJSON: Buffer; - clientData: any; - signature: Buffer; - challenge: string; -}) { - if (clientData.type !== "webauthn.get") { - throw new Error("type is not webauthn.get"); - } - - if (hash(clientData.challenge).toString("hex") !== challenge) { - throw new Error("challenge mismatch"); - } - if (clientData.origin !== `${config.scheme}://${config.host}`) { - throw new Error("origin mismatch"); - } - - const verificationData = Buffer.concat( - [authenticatorData, hash(clientDataJSON)], - 32 + authenticatorData.length, - ); - - return crypto - .createVerify("SHA256") - .update(verificationData) - .verify(PEMString(publicKey), signature); -} - -export const procedures = { - none: { - verify({ publicKey }: { publicKey: Map<number, Buffer> }) { - const negTwo = publicKey.get(-2); - - if (!negTwo || negTwo.length !== 32) { - throw new Error("invalid or no -2 key given"); - } - const negThree = publicKey.get(-3); - if (!negThree || negThree.length !== 32) { - throw new Error("invalid or no -3 key given"); - } - - const publicKeyU2F = Buffer.concat( - [ECC_PRELUDE, negTwo, negThree], - 1 + 32 + 32, - ); - - return { - publicKey: publicKeyU2F, - valid: true, - }; - }, - }, - "android-key": { - verify({ - attStmt, - authenticatorData, - clientDataHash, - publicKey, - rpIdHash, - credentialId, - }: { - attStmt: any; - authenticatorData: Buffer; - clientDataHash: Buffer; - publicKey: Map<number, any>; - rpIdHash: Buffer; - credentialId: Buffer; - }) { - if (attStmt.alg !== -7) { - throw new Error("alg mismatch"); - } - - const verificationData = Buffer.concat([ - authenticatorData, - clientDataHash, - ]); - - const attCert: Buffer = attStmt.x5c[0]; - - const negTwo = publicKey.get(-2); - - if (!negTwo || negTwo.length !== 32) { - throw new Error("invalid or no -2 key given"); - } - const negThree = publicKey.get(-3); - if (!negThree || negThree.length !== 32) { - throw new Error("invalid or no -3 key given"); - } - - const publicKeyData = Buffer.concat( - [ECC_PRELUDE, negTwo, negThree], - 1 + 32 + 32, - ); - - if (!attCert.equals(publicKeyData)) { - throw new Error("public key mismatch"); - } - - const isValid = crypto - .createVerify("SHA256") - .update(verificationData) - .verify(PEMString(attCert), attStmt.sig); - - // TODO: Check 'attestationChallenge' field in extension of cert matches hash(clientDataJSON) - - return { - valid: isValid, - publicKey: publicKeyData, - }; - }, - }, - // what a stupid attestation - "android-safetynet": { - verify({ - attStmt, - authenticatorData, - clientDataHash, - publicKey, - rpIdHash, - credentialId, - }: { - attStmt: any; - authenticatorData: Buffer; - clientDataHash: Buffer; - publicKey: Map<number, any>; - rpIdHash: Buffer; - credentialId: Buffer; - }) { - const verificationData = hash( - Buffer.concat([authenticatorData, clientDataHash]), - ); - - const jwsParts = attStmt.response.toString("utf-8").split("."); - - const header = JSON.parse(base64URLDecode(jwsParts[0]).toString("utf-8")); - const response = JSON.parse( - base64URLDecode(jwsParts[1]).toString("utf-8"), - ); - const signature = jwsParts[2]; - - if (!verificationData.equals(Buffer.from(response.nonce, "base64"))) { - throw new Error("invalid nonce"); - } - - const certificateChain = header.x5c - .map((key: any) => PEMString(key)) - .concat([GSR2]); - - if (getCertSubject(certificateChain[0]).CN !== "attest.android.com") { - throw new Error("invalid common name"); - } - - if (!verifyCertificateChain(certificateChain)) { - throw new Error("Invalid certificate chain!"); - } - - const signatureBase = Buffer.from( - `${jwsParts[0]}.${jwsParts[1]}`, - "utf-8", - ); - - const valid = crypto - .createVerify("sha256") - .update(signatureBase) - .verify(certificateChain[0], base64URLDecode(signature)); - - const negTwo = publicKey.get(-2); - - if (!negTwo || negTwo.length !== 32) { - throw new Error("invalid or no -2 key given"); - } - const negThree = publicKey.get(-3); - if (!negThree || negThree.length !== 32) { - throw new Error("invalid or no -3 key given"); - } - - const publicKeyData = Buffer.concat( - [ECC_PRELUDE, negTwo, negThree], - 1 + 32 + 32, - ); - return { - valid, - publicKey: publicKeyData, - }; - }, - }, - packed: { - verify({ - attStmt, - authenticatorData, - clientDataHash, - publicKey, - rpIdHash, - credentialId, - }: { - attStmt: any; - authenticatorData: Buffer; - clientDataHash: Buffer; - publicKey: Map<number, any>; - rpIdHash: Buffer; - credentialId: Buffer; - }) { - const verificationData = Buffer.concat([ - authenticatorData, - clientDataHash, - ]); - - if (attStmt.x5c) { - const attCert = attStmt.x5c[0]; - - const validSignature = crypto - .createVerify("SHA256") - .update(verificationData) - .verify(PEMString(attCert), attStmt.sig); - - const negTwo = publicKey.get(-2); - - if (!negTwo || negTwo.length !== 32) { - throw new Error("invalid or no -2 key given"); - } - const negThree = publicKey.get(-3); - if (!negThree || negThree.length !== 32) { - throw new Error("invalid or no -3 key given"); - } - - const publicKeyData = Buffer.concat( - [ECC_PRELUDE, negTwo, negThree], - 1 + 32 + 32, - ); - - return { - valid: validSignature, - publicKey: publicKeyData, - }; - } else if (attStmt.ecdaaKeyId) { - // https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-ecdaa-algorithm-v2.0-id-20180227.html#ecdaa-verify-operation - throw new Error("ECDAA-Verify is not supported"); - } else { - if (attStmt.alg !== -7) throw new Error("alg mismatch"); - - throw new Error("self attestation is not supported"); - } - }, - }, - - "fido-u2f": { - verify({ - attStmt, - authenticatorData, - clientDataHash, - publicKey, - rpIdHash, - credentialId, - }: { - attStmt: any; - authenticatorData: Buffer; - clientDataHash: Buffer; - publicKey: Map<number, any>; - rpIdHash: Buffer; - credentialId: Buffer; - }) { - const x5c: Buffer[] = attStmt.x5c; - if (x5c.length !== 1) { - throw new Error("x5c length does not match expectation"); - } - - const attCert = x5c[0]; - - // TODO: make sure attCert is an Elliptic Curve (EC) public key over the P-256 curve - - const negTwo: Buffer = publicKey.get(-2); - - if (!negTwo || negTwo.length !== 32) { - throw new Error("invalid or no -2 key given"); - } - const negThree: Buffer = publicKey.get(-3); - if (!negThree || negThree.length !== 32) { - throw new Error("invalid or no -3 key given"); - } - - const publicKeyU2F = Buffer.concat( - [ECC_PRELUDE, negTwo, negThree], - 1 + 32 + 32, - ); - - const verificationData = Buffer.concat([ - NULL_BYTE, - rpIdHash, - clientDataHash, - credentialId, - publicKeyU2F, - ]); - - const validSignature = crypto - .createVerify("SHA256") - .update(verificationData) - .verify(PEMString(attCert), attStmt.sig); - - return { - valid: validSignature, - publicKey: publicKeyU2F, - }; - }, - }, -}; diff --git a/packages/backend/src/server/api/api-handler.ts b/packages/backend/src/server/api/api-handler.ts deleted file mode 100644 index 99a12fd110..0000000000 --- a/packages/backend/src/server/api/api-handler.ts +++ /dev/null @@ -1,123 +0,0 @@ -import type Koa from "koa"; - -import type { User } from "@/models/entities/user.js"; -import { UserIps } from "@/models/index.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import type { IEndpoint } from "./endpoints.js"; -import authenticate, { AuthenticationError } from "./authenticate.js"; -import call from "./call.js"; -import { ApiError } from "./error.js"; - -const userIpHistories = new Map<User["id"], Set<string>>(); - -setInterval(() => { - userIpHistories.clear(); -}, 1000 * 60 * 60); - -export default (endpoint: IEndpoint, ctx: Koa.Context) => - new Promise<void>((res) => { - const body = ctx.is("multipart/form-data") - ? (ctx.request as any).body - : ctx.method === "GET" - ? ctx.query - : ctx.request.body; - - const reply = (x?: any, y?: ApiError) => { - if (x == null) { - ctx.status = 204; - } else if (typeof x === "number" && y) { - ctx.status = x; - ctx.body = { - error: { - message: y!.message, - code: y!.code, - id: y!.id, - kind: y!.kind, - ...(y!.info ? { info: y!.info } : {}), - }, - }; - } else { - // 文字列を返す場合は、JSON.stringify通さないとJSONと認識されない - ctx.body = typeof x === "string" ? JSON.stringify(x) : x; - } - res(); - }; - - // Authentication - // for GET requests, do not even pass on the body parameter as it is considered unsafe - authenticate( - ctx.headers.authorization, - ctx.method === "GET" ? null : body["i"], - ) - .then(([user, app]) => { - // API invoking - call(endpoint.name, user, app, body, ctx) - .then((res: any) => { - if ( - ctx.method === "GET" && - endpoint.meta.cacheSec && - !body["i"] && - !user - ) { - ctx.set( - "Cache-Control", - `public, max-age=${endpoint.meta.cacheSec}`, - ); - } - reply(res); - }) - .catch((e: ApiError) => { - reply( - e.httpStatusCode - ? e.httpStatusCode - : e.kind === "client" - ? 400 - : 500, - e, - ); - }); - - // Log IP - if (user) { - fetchMeta().then((meta) => { - if (!meta.enableIpLogging) return; - const ip = ctx.ip; - const ips = userIpHistories.get(user.id); - if (ips == null || !ips.has(ip)) { - if (ips == null) { - userIpHistories.set(user.id, new Set([ip])); - } else { - ips.add(ip); - } - - try { - UserIps.createQueryBuilder() - .insert() - .values({ - createdAt: new Date(), - userId: user.id, - ip: ip, - }) - .orIgnore(true) - .execute(); - } catch {} - } - }); - } - }) - .catch((e) => { - if (e instanceof AuthenticationError) { - ctx.response.status = 403; - ctx.response.set("WWW-Authenticate", "Bearer"); - ctx.response.body = { - message: `Authentication failed: ${e.message}`, - code: "AUTHENTICATION_FAILED", - id: "b0a7f5f8-dc2f-4171-b91f-de88ad238e14", - kind: "client", - }; - res(); - } else { - reply(500, new ApiError()); - } - }); - }); diff --git a/packages/backend/src/server/api/authenticate.ts b/packages/backend/src/server/api/authenticate.ts deleted file mode 100644 index 42274ad2a4..0000000000 --- a/packages/backend/src/server/api/authenticate.ts +++ /dev/null @@ -1,103 +0,0 @@ -import isNativeToken from "./common/is-native-token.js"; -import type { CacheableLocalUser, ILocalUser } from "@/models/entities/user.js"; -import { Users, AccessTokens, Apps } from "@/models/index.js"; -import type { AccessToken } from "@/models/entities/access-token.js"; -import { Cache } from "@/misc/cache.js"; -import type { App } from "@/models/entities/app.js"; -import { - localUserByIdCache, - localUserByNativeTokenCache, -} from "@/services/user-cache.js"; - -const appCache = new Cache<App>(Infinity); - -export class AuthenticationError extends Error { - constructor(message: string) { - super(message); - this.name = "AuthenticationError"; - } -} - -export default async ( - authorization: string | null | undefined, - bodyToken: string | null, -): Promise< - [CacheableLocalUser | null | undefined, AccessToken | null | undefined] -> => { - let token: string | null = null; - - // check if there is an authorization header set - if (authorization != null) { - if (bodyToken != null) { - throw new AuthenticationError("using multiple authorization schemes"); - } - - // check if OAuth 2.0 Bearer tokens are being used - // Authorization schemes are case insensitive - if (authorization.substring(0, 7).toLowerCase() === "bearer ") { - token = authorization.substring(7); - } else { - throw new AuthenticationError("unsupported authentication scheme"); - } - } else if (bodyToken != null) { - token = bodyToken; - } else { - return [null, null]; - } - - if (isNativeToken(token)) { - const user = await localUserByNativeTokenCache.fetch( - token, - () => Users.findOneBy({ token }) as Promise<ILocalUser | null>, - ); - - if (user == null) { - throw new AuthenticationError("unknown token"); - } - - return [user, null]; - } else { - const accessToken = await AccessTokens.findOne({ - where: [ - { - hash: token.toLowerCase(), // app - }, - { - token: token, // miauth - }, - ], - }); - - if (accessToken == null) { - throw new AuthenticationError("unknown token"); - } - - AccessTokens.update(accessToken.id, { - lastUsedAt: new Date(), - }); - - const user = await localUserByIdCache.fetch( - accessToken.userId, - () => - Users.findOneBy({ - id: accessToken.userId, - }) as Promise<ILocalUser>, - ); - - if (accessToken.appId) { - const app = await appCache.fetch(accessToken.appId, () => - Apps.findOneByOrFail({ id: accessToken.appId! }), - ); - - return [ - user, - { - id: accessToken.id, - permission: app.permission, - } as AccessToken, - ]; - } else { - return [user, accessToken]; - } - } -}; diff --git a/packages/backend/src/server/api/call.ts b/packages/backend/src/server/api/call.ts deleted file mode 100644 index 45471ed564..0000000000 --- a/packages/backend/src/server/api/call.ts +++ /dev/null @@ -1,192 +0,0 @@ -import { performance } from "perf_hooks"; -import type Koa from "koa"; -import type { CacheableLocalUser } from "@/models/entities/user.js"; -import { User } from "@/models/entities/user.js"; -import type { AccessToken } from "@/models/entities/access-token.js"; -import { getIpHash } from "@/misc/get-ip-hash.js"; -import { limiter } from "./limiter.js"; -import type { IEndpointMeta } from "./endpoints.js"; -import endpoints from "./endpoints.js"; -import compatibility from "./compatibility.js"; -import { ApiError } from "./error.js"; -import { apiLogger } from "./logger.js"; -import type { AccessToken } from "@/models/entities/access-token.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; - -const accessDenied = { - message: "Access denied.", - code: "ACCESS_DENIED", - id: "56f35758-7dd5-468b-8439-5d6fb8ec9b8e", -}; - -export default async ( - endpoint: string, - user: CacheableLocalUser | null | undefined, - token: AccessToken | null | undefined, - data: any, - ctx?: Koa.Context, -) => { - const isSecure = user != null && token == null; - const isModerator = user != null && (user.isModerator || user.isAdmin); - - const ep = - endpoints.find((e) => e.name === endpoint) || - compatibility.find((e) => e.name === endpoint); - - if (ep == null) { - throw new ApiError({ - message: "No such endpoint.", - code: "NO_SUCH_ENDPOINT", - id: "f8080b67-5f9c-4eb7-8c18-7f1eeae8f709", - httpStatusCode: 404, - }); - } - - if (ep.meta.secure && !isSecure) { - throw new ApiError(accessDenied); - } - - if (ep.meta.limit) { - // koa will automatically load the `X-Forwarded-For` header if `proxy: true` is configured in the app. - let limitActor: string; - if (user) { - limitActor = user.id; - } else { - limitActor = getIpHash(ctx!.ip); - } - - const limit = Object.assign({}, ep.meta.limit); - - if (!limit.key) { - limit.key = ep.name; - } - - // Rate limit - await limiter( - limit as IEndpointMeta["limit"] & { key: NonNullable<string> }, - limitActor, - ).catch((e) => { - throw new ApiError({ - message: "Rate limit exceeded. Please try again later.", - code: "RATE_LIMIT_EXCEEDED", - id: "d5826d14-3982-4d2e-8011-b9e9f02499ef", - httpStatusCode: 429, - }); - }); - } - - if (ep.meta.requireCredential && user == null) { - throw new ApiError({ - message: "Credential required.", - code: "CREDENTIAL_REQUIRED", - id: "1384574d-a912-4b81-8601-c7b1c4085df1", - httpStatusCode: 401, - }); - } - - if (ep.meta.requireCredential && user!.isSuspended) { - throw new ApiError({ - message: "Your account has been suspended.", - code: "YOUR_ACCOUNT_SUSPENDED", - id: "a8c724b3-6e9c-4b46-b1a8-bc3ed6258370", - httpStatusCode: 403, - }); - } - - if (ep.meta.requireAdmin && !user!.isAdmin) { - throw new ApiError(accessDenied, { reason: "You are not the admin." }); - } - - if (ep.meta.requireModerator && !isModerator) { - throw new ApiError(accessDenied, { reason: "You are not a moderator." }); - } - - if ( - token && - ep.meta.kind && - !token.permission.some((p) => p === ep.meta.kind) - ) { - throw new ApiError({ - message: - "Your app does not have the necessary permissions to use this endpoint.", - code: "PERMISSION_DENIED", - id: "1370e5b7-d4eb-4566-bb1d-7748ee6a1838", - }); - } - - // private mode - const meta = await fetchMeta(); - if ( - meta.privateMode && - ep.meta.requireCredentialPrivateMode && - user == null - ) { - throw new ApiError({ - message: "Credential required.", - code: "CREDENTIAL_REQUIRED", - id: "1384574d-a912-4b81-8601-c7b1c4085df1", - httpStatusCode: 401, - }); - } - - // Cast non JSON input - if ((ep.meta.requireFile || ctx?.method === "GET") && ep.params.properties) { - for (const k of Object.keys(ep.params.properties)) { - const param = ep.params.properties![k]; - if ( - ["boolean", "number", "integer"].includes(param.type ?? "") && - typeof data[k] === "string" - ) { - try { - data[k] = JSON.parse(data[k]); - } catch (e) { - throw new ApiError( - { - message: "Invalid param.", - code: "INVALID_PARAM", - id: "0b5f1631-7c1a-41a6-b399-cce335f34d85", - }, - { - param: k, - reason: `cannot cast to ${param.type}`, - }, - ); - } - } - } - } - - // API invoking - const before = performance.now(); - return await ep - .exec(data, user, token, ctx?.file, ctx?.ip, ctx?.headers) - .catch((e: Error) => { - if (e instanceof ApiError) { - throw e; - } else { - apiLogger.error(`Internal error occurred in ${ep.name}: ${e.message}`, { - ep: ep.name, - ps: data, - e: { - message: e.message, - code: e.name, - stack: e.stack, - }, - }); - throw new ApiError(null, { - e: { - message: e.message, - code: e.name, - stack: e.stack, - }, - }); - } - }) - .finally(() => { - const after = performance.now(); - const time = after - before; - if (time > 1000) { - apiLogger.warn(`SLOW API CALL DETECTED: ${ep.name} (${time}ms)`); - } - }); -}; diff --git a/packages/backend/src/server/api/common/generate-block-query.ts b/packages/backend/src/server/api/common/generate-block-query.ts deleted file mode 100644 index a37b607eb9..0000000000 --- a/packages/backend/src/server/api/common/generate-block-query.ts +++ /dev/null @@ -1,54 +0,0 @@ -import type { User } from "@/models/entities/user.js"; -import { Blockings } from "@/models/index.js"; -import type { SelectQueryBuilder } from "typeorm"; -import { Brackets } from "typeorm"; - -// ここでいうBlockedは被Blockedの意 -export function generateBlockedUserQuery( - q: SelectQueryBuilder<any>, - me: { id: User["id"] }, -) { - const blockingQuery = Blockings.createQueryBuilder("blocking") - .select("blocking.blockerId") - .where("blocking.blockeeId = :blockeeId", { blockeeId: me.id }); - - // 投稿の作者にブロックされていない かつ - // 投稿の返信先の作者にブロックされていない かつ - // 投稿の引用元の作者にブロックされていない - q.andWhere(`note.userId NOT IN (${blockingQuery.getQuery()})`) - .andWhere( - new Brackets((qb) => { - qb.where("note.replyUserId IS NULL").orWhere( - `note.replyUserId NOT IN (${blockingQuery.getQuery()})`, - ); - }), - ) - .andWhere( - new Brackets((qb) => { - qb.where("note.renoteUserId IS NULL").orWhere( - `note.renoteUserId NOT IN (${blockingQuery.getQuery()})`, - ); - }), - ); - - q.setParameters(blockingQuery.getParameters()); -} - -export function generateBlockQueryForUsers( - q: SelectQueryBuilder<any>, - me: { id: User["id"] }, -) { - const blockingQuery = Blockings.createQueryBuilder("blocking") - .select("blocking.blockeeId") - .where("blocking.blockerId = :blockerId", { blockerId: me.id }); - - const blockedQuery = Blockings.createQueryBuilder("blocking") - .select("blocking.blockerId") - .where("blocking.blockeeId = :blockeeId", { blockeeId: me.id }); - - q.andWhere(`user.id NOT IN (${blockingQuery.getQuery()})`); - q.setParameters(blockingQuery.getParameters()); - - q.andWhere(`user.id NOT IN (${blockedQuery.getQuery()})`); - q.setParameters(blockedQuery.getParameters()); -} diff --git a/packages/backend/src/server/api/common/generate-channel-query.ts b/packages/backend/src/server/api/common/generate-channel-query.ts deleted file mode 100644 index 318062266e..0000000000 --- a/packages/backend/src/server/api/common/generate-channel-query.ts +++ /dev/null @@ -1,35 +0,0 @@ -import type { User } from "@/models/entities/user.js"; -import { ChannelFollowings } from "@/models/index.js"; -import type { SelectQueryBuilder } from "typeorm"; -import { Brackets } from "typeorm"; - -export function generateChannelQuery( - q: SelectQueryBuilder<any>, - me?: { id: User["id"] } | null, -) { - if (me == null) { - q.andWhere("note.channelId IS NULL"); - } else { - q.leftJoinAndSelect("note.channel", "channel"); - - const channelFollowingQuery = ChannelFollowings.createQueryBuilder( - "channelFollowing", - ) - .select("channelFollowing.followeeId") - .where("channelFollowing.followerId = :followerId", { - followerId: me.id, - }); - - q.andWhere( - new Brackets((qb) => { - qb - // チャンネルのノートではない - .where("note.channelId IS NULL") - // または自分がフォローしているチャンネルのノート - .orWhere(`note.channelId IN (${channelFollowingQuery.getQuery()})`); - }), - ); - - q.setParameters(channelFollowingQuery.getParameters()); - } -} diff --git a/packages/backend/src/server/api/common/generate-muted-note-query.ts b/packages/backend/src/server/api/common/generate-muted-note-query.ts deleted file mode 100644 index 86da2ea883..0000000000 --- a/packages/backend/src/server/api/common/generate-muted-note-query.ts +++ /dev/null @@ -1,16 +0,0 @@ -import type { User } from "@/models/entities/user.js"; -import { MutedNotes } from "@/models/index.js"; -import type { SelectQueryBuilder } from "typeorm"; - -export function generateMutedNoteQuery( - q: SelectQueryBuilder<any>, - me: { id: User["id"] }, -) { - const mutedQuery = MutedNotes.createQueryBuilder("muted") - .select("muted.noteId") - .where("muted.userId = :userId", { userId: me.id }); - - q.andWhere(`note.id NOT IN (${mutedQuery.getQuery()})`); - - q.setParameters(mutedQuery.getParameters()); -} diff --git a/packages/backend/src/server/api/common/generate-muted-note-thread-query.ts b/packages/backend/src/server/api/common/generate-muted-note-thread-query.ts deleted file mode 100644 index 61f44f4a76..0000000000 --- a/packages/backend/src/server/api/common/generate-muted-note-thread-query.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { User } from "@/models/entities/user.js"; -import { NoteThreadMutings } from "@/models/index.js"; -import type { SelectQueryBuilder } from "typeorm"; -import { Brackets } from "typeorm"; - -export function generateMutedNoteThreadQuery( - q: SelectQueryBuilder<any>, - me: { id: User["id"] }, -) { - const mutedQuery = NoteThreadMutings.createQueryBuilder("threadMuted") - .select("threadMuted.threadId") - .where("threadMuted.userId = :userId", { userId: me.id }); - - q.andWhere(`note.id NOT IN (${mutedQuery.getQuery()})`); - q.andWhere( - new Brackets((qb) => { - qb.where("note.threadId IS NULL").orWhere( - `note.threadId NOT IN (${mutedQuery.getQuery()})`, - ); - }), - ); - - q.setParameters(mutedQuery.getParameters()); -} diff --git a/packages/backend/src/server/api/common/generate-muted-user-query.ts b/packages/backend/src/server/api/common/generate-muted-user-query.ts deleted file mode 100644 index 3538fbf0af..0000000000 --- a/packages/backend/src/server/api/common/generate-muted-user-query.ts +++ /dev/null @@ -1,81 +0,0 @@ -import type { SelectQueryBuilder } from "typeorm"; -import { Brackets } from "typeorm"; -import type { User } from "@/models/entities/user.js"; -import { Mutings, UserProfiles } from "@/models/index.js"; - -export function generateMutedUserQuery( - q: SelectQueryBuilder<any>, - me: { id: User["id"] }, - exclude?: User, -) { - const mutingQuery = Mutings.createQueryBuilder("muting") - .select("muting.muteeId") - .where("muting.muterId = :muterId", { muterId: me.id }); - - if (exclude) { - mutingQuery.andWhere("muting.muteeId != :excludeId", { - excludeId: exclude.id, - }); - } - - const mutingInstanceQuery = UserProfiles.createQueryBuilder("user_profile") - .select("user_profile.mutedInstances") - .where("user_profile.userId = :muterId", { muterId: me.id }); - - // 投稿の作者をミュートしていない かつ - // 投稿の返信先の作者をミュートしていない かつ - // 投稿の引用元の作者をミュートしていない - q.andWhere(`note.userId NOT IN (${mutingQuery.getQuery()})`) - .andWhere( - new Brackets((qb) => { - qb.where("note.replyUserId IS NULL").orWhere( - `note.replyUserId NOT IN (${mutingQuery.getQuery()})`, - ); - }), - ) - .andWhere( - new Brackets((qb) => { - qb.where("note.renoteUserId IS NULL").orWhere( - `note.renoteUserId NOT IN (${mutingQuery.getQuery()})`, - ); - }), - ) - // mute instances - .andWhere( - new Brackets((qb) => { - qb.andWhere("note.userHost IS NULL").orWhere( - `NOT ((${mutingInstanceQuery.getQuery()})::jsonb ? note.userHost)`, - ); - }), - ) - .andWhere( - new Brackets((qb) => { - qb.where("note.replyUserHost IS NULL").orWhere( - `NOT ((${mutingInstanceQuery.getQuery()})::jsonb ? note.replyUserHost)`, - ); - }), - ) - .andWhere( - new Brackets((qb) => { - qb.where("note.renoteUserHost IS NULL").orWhere( - `NOT ((${mutingInstanceQuery.getQuery()})::jsonb ? note.renoteUserHost)`, - ); - }), - ); - - q.setParameters(mutingQuery.getParameters()); - q.setParameters(mutingInstanceQuery.getParameters()); -} - -export function generateMutedUserQueryForUsers( - q: SelectQueryBuilder<any>, - me: { id: User["id"] }, -) { - const mutingQuery = Mutings.createQueryBuilder("muting") - .select("muting.muteeId") - .where("muting.muterId = :muterId", { muterId: me.id }); - - q.andWhere(`user.id NOT IN (${mutingQuery.getQuery()})`); - - q.setParameters(mutingQuery.getParameters()); -} diff --git a/packages/backend/src/server/api/common/generate-native-user-token.ts b/packages/backend/src/server/api/common/generate-native-user-token.ts deleted file mode 100644 index 5a8b41b70e..0000000000 --- a/packages/backend/src/server/api/common/generate-native-user-token.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { secureRndstr } from "@/misc/secure-rndstr.js"; - -export default () => secureRndstr(16, true); diff --git a/packages/backend/src/server/api/common/generate-replies-query.ts b/packages/backend/src/server/api/common/generate-replies-query.ts deleted file mode 100644 index 140c1d74a0..0000000000 --- a/packages/backend/src/server/api/common/generate-replies-query.ts +++ /dev/null @@ -1,47 +0,0 @@ -import type { User } from "@/models/entities/user.js"; -import type { SelectQueryBuilder } from "typeorm"; -import { Brackets } from "typeorm"; - -export function generateRepliesQuery( - q: SelectQueryBuilder<any>, - me?: Pick<User, "id" | "showTimelineReplies"> | null, -) { - if (me == null) { - q.andWhere( - new Brackets((qb) => { - qb.where("note.replyId IS NULL") // 返信ではない - .orWhere( - new Brackets((qb) => { - qb.where( - // 返信だけど投稿者自身への返信 - "note.replyId IS NOT NULL", - ).andWhere("note.replyUserId = note.userId"); - }), - ); - }), - ); - } else if (!me.showTimelineReplies) { - q.andWhere( - new Brackets((qb) => { - qb.where("note.replyId IS NULL") // 返信ではない - .orWhere("note.replyUserId = :meId", { meId: me.id }) // 返信だけど自分のノートへの返信 - .orWhere( - new Brackets((qb) => { - qb.where( - // 返信だけど自分の行った返信 - "note.replyId IS NOT NULL", - ).andWhere("note.userId = :meId", { meId: me.id }); - }), - ) - .orWhere( - new Brackets((qb) => { - qb.where( - // 返信だけど投稿者自身への返信 - "note.replyId IS NOT NULL", - ).andWhere("note.replyUserId = note.userId"); - }), - ); - }), - ); - } -} diff --git a/packages/backend/src/server/api/common/generate-visibility-query.ts b/packages/backend/src/server/api/common/generate-visibility-query.ts deleted file mode 100644 index c434df0820..0000000000 --- a/packages/backend/src/server/api/common/generate-visibility-query.ts +++ /dev/null @@ -1,61 +0,0 @@ -import type { User } from "@/models/entities/user.js"; -import { Followings } from "@/models/index.js"; -import type { SelectQueryBuilder } from "typeorm"; -import { Brackets } from "typeorm"; - -export function generateVisibilityQuery( - q: SelectQueryBuilder<any>, - me?: { id: User["id"] } | null, -) { - // This code must always be synchronized with the checks in Notes.isVisibleForMe. - if (me == null) { - q.andWhere( - new Brackets((qb) => { - qb.where(`note.visibility = 'public'`).orWhere( - `note.visibility = 'home'`, - ); - }), - ); - } else { - const followingQuery = Followings.createQueryBuilder("following") - .select("following.followeeId") - .where("following.followerId = :meId"); - - q.andWhere( - new Brackets((qb) => { - qb - // 公開投稿である - .where( - new Brackets((qb) => { - qb.where(`note.visibility = 'public'`).orWhere( - `note.visibility = 'home'`, - ); - }), - ) - // または 自分自身 - .orWhere("note.userId = :meId") - // または 自分宛て - .orWhere(":meId = ANY(note.visibleUserIds)") - .orWhere(":meId = ANY(note.mentions)") - .orWhere( - new Brackets((qb) => { - qb - // または フォロワー宛ての投稿であり、 - .where(`note.visibility = 'followers'`) - .andWhere( - new Brackets((qb) => { - qb - // 自分がフォロワーである - .where(`note.userId IN (${followingQuery.getQuery()})`) - // または 自分の投稿へのリプライ - .orWhere("note.replyUserId = :meId"); - }), - ); - }), - ); - }), - ); - - q.setParameters({ meId: me.id }); - } -} diff --git a/packages/backend/src/server/api/common/generated-muted-renote-query.ts b/packages/backend/src/server/api/common/generated-muted-renote-query.ts deleted file mode 100644 index 3fcd9b28e8..0000000000 --- a/packages/backend/src/server/api/common/generated-muted-renote-query.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { Brackets, SelectQueryBuilder } from "typeorm"; -import { User } from "@/models/entities/user.js"; -import { RenoteMutings } from "@/models/index.js"; - -export function generateMutedUserRenotesQueryForNotes( - q: SelectQueryBuilder<any>, - me: { id: User["id"] }, -): void { - const mutingQuery = RenoteMutings.createQueryBuilder("renote_muting") - .select("renote_muting.muteeId") - .where("renote_muting.muterId = :muterId", { muterId: me.id }); - - q.andWhere( - new Brackets((qb) => { - qb.where( - new Brackets((qb) => { - qb.where("note.renoteId IS NOT NULL"); - qb.andWhere("note.text IS NULL"); - qb.andWhere(`note.userId NOT IN (${mutingQuery.getQuery()})`); - }), - ) - .orWhere("note.renoteId IS NULL") - .orWhere("note.text IS NOT NULL"); - }), - ); - - q.setParameters(mutingQuery.getParameters()); -} diff --git a/packages/backend/src/server/api/common/getters.ts b/packages/backend/src/server/api/common/getters.ts deleted file mode 100644 index fd7580775a..0000000000 --- a/packages/backend/src/server/api/common/getters.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { IdentifiableError } from "@/misc/identifiable-error.js"; -import type { User } from "@/models/entities/user.js"; -import type { Note } from "@/models/entities/note.js"; -import { Notes, Users } from "@/models/index.js"; -import { generateVisibilityQuery } from "./generate-visibility-query.js"; - -/** - * Get note for API processing, taking into account visibility. - */ -export async function getNote( - noteId: Note["id"], - me: { id: User["id"] } | null, -) { - const query = Notes.createQueryBuilder("note").where("note.id = :id", { - id: noteId, - }); - - generateVisibilityQuery(query, me); - - const note = await query.getOne(); - - if (note == null) { - throw new IdentifiableError( - "9725d0ce-ba28-4dde-95a7-2cbb2c15de24", - "No such note.", - ); - } - - return note; -} - -/** - * Get user for API processing - */ -export async function getUser(userId: User["id"]) { - const user = await Users.findOneBy({ id: userId }); - - if (user == null) { - throw new IdentifiableError( - "15348ddd-432d-49c2-8a5a-8069753becff", - "No such user.", - ); - } - - return user; -} - -/** - * Get remote user for API processing - */ -export async function getRemoteUser(userId: User["id"]) { - const user = await getUser(userId); - - if (!Users.isRemoteUser(user)) { - throw new Error("user is not a remote user"); - } - - return user; -} - -/** - * Get local user for API processing - */ -export async function getLocalUser(userId: User["id"]) { - const user = await getUser(userId); - - if (!Users.isLocalUser(user)) { - throw new Error("user is not a local user"); - } - - return user; -} diff --git a/packages/backend/src/server/api/common/inject-featured.ts b/packages/backend/src/server/api/common/inject-featured.ts deleted file mode 100644 index 30ba3eca93..0000000000 --- a/packages/backend/src/server/api/common/inject-featured.ts +++ /dev/null @@ -1,53 +0,0 @@ -import rndstr from "rndstr"; -import type { Note } from "@/models/entities/note.js"; -import type { User } from "@/models/entities/user.js"; -import { Notes, UserProfiles, NoteReactions } from "@/models/index.js"; -import { generateMutedUserQuery } from "./generate-muted-user-query.js"; -import { generateBlockedUserQuery } from "./generate-block-query.js"; - -// TODO: リアクション、Renote、返信などをしたノートは除外する - -export async function injectFeatured(timeline: Note[], user?: User | null) { - if (timeline.length < 5) return; - - if (user) { - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - if (!profile.injectFeaturedNote) return; - } - - const max = 30; - const day = 1000 * 60 * 60 * 24 * 3; // 3日前まで - - const query = Notes.createQueryBuilder("note") - .addSelect("note.score") - .where("note.userHost IS NULL") - .andWhere("note.score > 0") - .andWhere("note.createdAt > :date", { date: new Date(Date.now() - day) }) - .andWhere(`note.visibility = 'public'`) - .innerJoinAndSelect("note.user", "user"); - - if (user) { - query.andWhere("note.userId != :userId", { userId: user.id }); - - generateMutedUserQuery(query, user); - generateBlockedUserQuery(query, user); - - const reactionQuery = NoteReactions.createQueryBuilder("reaction") - .select("reaction.noteId") - .where("reaction.userId = :userId", { userId: user.id }); - - query.andWhere(`note.id NOT IN (${reactionQuery.getQuery()})`); - } - - const notes = await query.orderBy("note.score", "DESC").take(max).getMany(); - - if (notes.length === 0) return; - - // Pick random one - const featured = notes[Math.floor(Math.random() * notes.length)]; - - (featured as any)._featuredId_ = rndstr("a-z0-9", 8); - - // Inject featured - timeline.splice(3, 0, featured); -} diff --git a/packages/backend/src/server/api/common/inject-promo.ts b/packages/backend/src/server/api/common/inject-promo.ts deleted file mode 100644 index dcc4e5f3fa..0000000000 --- a/packages/backend/src/server/api/common/inject-promo.ts +++ /dev/null @@ -1,36 +0,0 @@ -import rndstr from "rndstr"; -import type { Note } from "@/models/entities/note.js"; -import type { User } from "@/models/entities/user.js"; -import { PromoReads, PromoNotes, Notes, Users } from "@/models/index.js"; - -export async function injectPromo(timeline: Note[], user?: User | null) { - if (timeline.length < 5) return; - - // TODO: readやexpireフィルタはクエリ側でやる - - const reads = user - ? await PromoReads.findBy({ - userId: user.id, - }) - : []; - - let promos = await PromoNotes.find(); - - promos = promos.filter((n) => n.expiresAt.getTime() > Date.now()); - promos = promos.filter((n) => !reads.map((r) => r.noteId).includes(n.noteId)); - - if (promos.length === 0) return; - - // Pick random promo - const promo = promos[Math.floor(Math.random() * promos.length)]; - - const note = await Notes.findOneByOrFail({ id: promo.noteId }); - - // Join - note.user = await Users.findOneByOrFail({ id: note.userId }); - - (note as any)._prId_ = rndstr("a-z0-9", 8); - - // Inject promo - timeline.splice(3, 0, note); -} diff --git a/packages/backend/src/server/api/common/is-native-token.ts b/packages/backend/src/server/api/common/is-native-token.ts deleted file mode 100644 index 2833c570c8..0000000000 --- a/packages/backend/src/server/api/common/is-native-token.ts +++ /dev/null @@ -1 +0,0 @@ -export default (token: string) => token.length === 16; diff --git a/packages/backend/src/server/api/common/make-pagination-query.ts b/packages/backend/src/server/api/common/make-pagination-query.ts deleted file mode 100644 index a2c3275693..0000000000 --- a/packages/backend/src/server/api/common/make-pagination-query.ts +++ /dev/null @@ -1,42 +0,0 @@ -import type { SelectQueryBuilder } from "typeorm"; - -export function makePaginationQuery<T>( - q: SelectQueryBuilder<T>, - sinceId?: string, - untilId?: string, - sinceDate?: number, - untilDate?: number, -) { - if (sinceId && untilId) { - q.andWhere(`${q.alias}.id > :sinceId`, { sinceId: sinceId }); - q.andWhere(`${q.alias}.id < :untilId`, { untilId: untilId }); - q.orderBy(`${q.alias}.id`, "DESC"); - } else if (sinceId) { - q.andWhere(`${q.alias}.id > :sinceId`, { sinceId: sinceId }); - q.orderBy(`${q.alias}.id`, "ASC"); - } else if (untilId) { - q.andWhere(`${q.alias}.id < :untilId`, { untilId: untilId }); - q.orderBy(`${q.alias}.id`, "DESC"); - } else if (sinceDate && untilDate) { - q.andWhere(`${q.alias}.createdAt > :sinceDate`, { - sinceDate: new Date(sinceDate), - }); - q.andWhere(`${q.alias}.createdAt < :untilDate`, { - untilDate: new Date(untilDate), - }); - q.orderBy(`${q.alias}.createdAt`, "DESC"); - } else if (sinceDate) { - q.andWhere(`${q.alias}.createdAt > :sinceDate`, { - sinceDate: new Date(sinceDate), - }); - q.orderBy(`${q.alias}.createdAt`, "ASC"); - } else if (untilDate) { - q.andWhere(`${q.alias}.createdAt < :untilDate`, { - untilDate: new Date(untilDate), - }); - q.orderBy(`${q.alias}.createdAt`, "DESC"); - } else { - q.orderBy(`${q.alias}.id`, "DESC"); - } - return q; -} diff --git a/packages/backend/src/server/api/common/read-messaging-message.ts b/packages/backend/src/server/api/common/read-messaging-message.ts deleted file mode 100644 index fc22c843af..0000000000 --- a/packages/backend/src/server/api/common/read-messaging-message.ts +++ /dev/null @@ -1,179 +0,0 @@ -import { - publishMainStream, - publishGroupMessagingStream, -} from "@/services/stream.js"; -import { publishMessagingStream } from "@/services/stream.js"; -import { publishMessagingIndexStream } from "@/services/stream.js"; -import { pushNotification } from "@/services/push-notification.js"; -import type { User, IRemoteUser } from "@/models/entities/user.js"; -import type { MessagingMessage } from "@/models/entities/messaging-message.js"; -import { MessagingMessages, UserGroupJoinings, Users } from "@/models/index.js"; -import { In } from "typeorm"; -import { IdentifiableError } from "@/misc/identifiable-error.js"; -import type { UserGroup } from "@/models/entities/user-group.js"; -import { toArray } from "@/prelude/array.js"; -import { renderReadActivity } from "@/remote/activitypub/renderer/read.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import { deliver } from "@/queue/index.js"; -import orderedCollection from "@/remote/activitypub/renderer/ordered-collection.js"; - -/** - * Mark messages as read - */ -export async function readUserMessagingMessage( - userId: User["id"], - otherpartyId: User["id"], - messageIds: MessagingMessage["id"][], -) { - if (messageIds.length === 0) return; - - const messages = await MessagingMessages.findBy({ - id: In(messageIds), - }); - - for (const message of messages) { - if (message.recipientId !== userId) { - throw new IdentifiableError( - "e140a4bf-49ce-4fb6-b67c-b78dadf6b52f", - "Access denied (user).", - ); - } - } - - // Update documents - await MessagingMessages.update( - { - id: In(messageIds), - userId: otherpartyId, - recipientId: userId, - isRead: false, - }, - { - isRead: true, - }, - ); - - // Publish event - publishMessagingStream(otherpartyId, userId, "read", messageIds); - publishMessagingIndexStream(userId, "read", messageIds); - - if (!(await Users.getHasUnreadMessagingMessage(userId))) { - // 全ての(いままで未読だった)自分宛てのメッセージを(これで)読みましたよというイベントを発行 - publishMainStream(userId, "readAllMessagingMessages"); - pushNotification(userId, "readAllMessagingMessages", undefined); - } else { - // そのユーザーとのメッセージで未読がなければイベント発行 - const count = await MessagingMessages.count({ - where: { - userId: otherpartyId, - recipientId: userId, - isRead: false, - }, - take: 1, - }); - - if (!count) { - pushNotification(userId, "readAllMessagingMessagesOfARoom", { - userId: otherpartyId, - }); - } - } -} - -/** - * Mark messages as read - */ -export async function readGroupMessagingMessage( - userId: User["id"], - groupId: UserGroup["id"], - messageIds: MessagingMessage["id"][], -) { - if (messageIds.length === 0) return; - - // check joined - const joining = await UserGroupJoinings.findOneBy({ - userId: userId, - userGroupId: groupId, - }); - - if (joining == null) { - throw new IdentifiableError( - "930a270c-714a-46b2-b776-ad27276dc569", - "Access denied (group).", - ); - } - - const messages = await MessagingMessages.findBy({ - id: In(messageIds), - }); - - const reads: MessagingMessage["id"][] = []; - - for (const message of messages) { - if (message.userId === userId) continue; - if (message.reads.includes(userId)) continue; - - // Update document - await MessagingMessages.createQueryBuilder() - .update() - .set({ - reads: (() => `array_append("reads", '${joining.userId}')`) as any, - }) - .where("id = :id", { id: message.id }) - .execute(); - - reads.push(message.id); - } - - // Publish event - publishGroupMessagingStream(groupId, "read", { - ids: reads, - userId: userId, - }); - publishMessagingIndexStream(userId, "read", reads); - - if (!(await Users.getHasUnreadMessagingMessage(userId))) { - // 全ての(いままで未読だった)自分宛てのメッセージを(これで)読みましたよというイベントを発行 - publishMainStream(userId, "readAllMessagingMessages"); - pushNotification(userId, "readAllMessagingMessages", undefined); - } else { - // そのグループにおいて未読がなければイベント発行 - const unreadExist = await MessagingMessages.createQueryBuilder("message") - .where("message.groupId = :groupId", { groupId: groupId }) - .andWhere("message.userId != :userId", { userId: userId }) - .andWhere("NOT (:userId = ANY(message.reads))", { userId: userId }) - .andWhere("message.createdAt > :joinedAt", { - joinedAt: joining.createdAt, - }) // 自分が加入する前の会話については、未読扱いしない - .getOne() - .then((x) => x != null); - - if (!unreadExist) { - pushNotification(userId, "readAllMessagingMessagesOfARoom", { groupId }); - } - } -} - -export async function deliverReadActivity( - user: { id: User["id"]; host: null }, - recipient: IRemoteUser, - messages: MessagingMessage | MessagingMessage[], -) { - messages = toArray(messages).filter((x) => x.uri); - const contents = messages.map((x) => renderReadActivity(user, x)); - - if (contents.length > 1) { - const collection = orderedCollection( - null, - contents.length, - undefined, - undefined, - contents, - ); - deliver(user, renderActivity(collection), recipient.inbox); - } else { - for (const content of contents) { - deliver(user, renderActivity(content), recipient.inbox); - } - } -} diff --git a/packages/backend/src/server/api/common/read-notification.ts b/packages/backend/src/server/api/common/read-notification.ts deleted file mode 100644 index 1fb1d642fe..0000000000 --- a/packages/backend/src/server/api/common/read-notification.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { In } from "typeorm"; -import { publishMainStream } from "@/services/stream.js"; -import { pushNotification } from "@/services/push-notification.js"; -import type { User } from "@/models/entities/user.js"; -import type { Notification } from "@/models/entities/notification.js"; -import { Notifications, Users } from "@/models/index.js"; - -export async function readNotification( - userId: User["id"], - notificationIds: Notification["id"][], -) { - if (notificationIds.length === 0) return; - - // Update documents - const result = await Notifications.update( - { - notifieeId: userId, - id: In(notificationIds), - isRead: false, - }, - { - isRead: true, - }, - ); - - if (result.affected === 0) return; - - if (!(await Users.getHasUnreadNotification(userId))) - return postReadAllNotifications(userId); - else return postReadNotifications(userId, notificationIds); -} - -export async function readNotificationByQuery( - userId: User["id"], - query: Record<string, any>, -) { - const notificationIds = await Notifications.findBy({ - ...query, - notifieeId: userId, - isRead: false, - }).then((notifications) => - notifications.map((notification) => notification.id), - ); - - return readNotification(userId, notificationIds); -} - -function postReadAllNotifications(userId: User["id"]) { - publishMainStream(userId, "readAllNotifications"); - return pushNotification(userId, "readAllNotifications", undefined); -} - -function postReadNotifications( - userId: User["id"], - notificationIds: Notification["id"][], -) { - publishMainStream(userId, "readNotifications", notificationIds); - return pushNotification(userId, "readNotifications", { notificationIds }); -} diff --git a/packages/backend/src/server/api/common/signin.ts b/packages/backend/src/server/api/common/signin.ts deleted file mode 100644 index a8a435843f..0000000000 --- a/packages/backend/src/server/api/common/signin.ts +++ /dev/null @@ -1,44 +0,0 @@ -import type Koa from "koa"; - -import config from "@/config/index.js"; -import type { ILocalUser } from "@/models/entities/user.js"; -import { Signins } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import { publishMainStream } from "@/services/stream.js"; - -export default function (ctx: Koa.Context, user: ILocalUser, redirect = false) { - if (redirect) { - //#region Cookie - ctx.cookies.set("igi", user.token!, { - path: "/", - // SEE: https://github.com/koajs/koa/issues/974 - // When using a SSL proxy it should be configured to add the "X-Forwarded-Proto: https" header - secure: config.url.startsWith("https"), - httpOnly: false, - }); - //#endregion - - ctx.redirect(config.url); - } else { - ctx.body = { - id: user.id, - i: user.token, - }; - ctx.status = 200; - } - - (async () => { - // Append signin history - const record = await Signins.insert({ - id: genId(), - createdAt: new Date(), - userId: user.id, - ip: ctx.ip, - headers: ctx.headers, - success: true, - }).then((x) => Signins.findOneByOrFail(x.identifiers[0])); - - // Publish signin event - publishMainStream(user.id, "signin", await Signins.pack(record)); - })(); -} diff --git a/packages/backend/src/server/api/common/signup.ts b/packages/backend/src/server/api/common/signup.ts deleted file mode 100644 index 6beae2c782..0000000000 --- a/packages/backend/src/server/api/common/signup.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { generateKeyPair } from "node:crypto"; -import generateUserToken from "./generate-native-user-token.js"; -import { User } from "@/models/entities/user.js"; -import { Users, UsedUsernames } from "@/models/index.js"; -import { UserProfile } from "@/models/entities/user-profile.js"; -import { IsNull } from "typeorm"; -import { genId } from "@/misc/gen-id.js"; -import { toPunyNullable } from "@/misc/convert-host.js"; -import { UserKeypair } from "@/models/entities/user-keypair.js"; -import { usersChart } from "@/services/chart/index.js"; -import { UsedUsername } from "@/models/entities/used-username.js"; -import { db } from "@/db/postgre.js"; -import config from "@/config/index.js"; -import { hashPassword } from "@/misc/password.js"; - -export async function signup(opts: { - username: User["username"]; - password?: string | null; - passwordHash?: UserProfile["password"] | null; - host?: string | null; -}) { - const { username, password, passwordHash, host } = opts; - let hash = passwordHash; - - const userCount = await Users.countBy({ - host: IsNull(), - }); - - if (config.maxUserSignups != null && userCount > config.maxUserSignups) { - throw new Error("MAX_USERS_REACHED"); - } - - // Validate username - if (!Users.validateLocalUsername(username)) { - throw new Error("INVALID_USERNAME"); - } - - if (password != null && passwordHash == null) { - // Validate password - if (!Users.validatePassword(password)) { - throw new Error("INVALID_PASSWORD"); - } - - // Generate hash of password - hash = await hashPassword(password); - } - - // Generate secret - const secret = generateUserToken(); - - // Check username duplication - if ( - await Users.findOneBy({ - usernameLower: username.toLowerCase(), - host: IsNull(), - }) - ) { - throw new Error("DUPLICATED_USERNAME"); - } - - // Check deleted username duplication - if (await UsedUsernames.findOneBy({ username: username.toLowerCase() })) { - throw new Error("USED_USERNAME"); - } - - const keyPair = await new Promise<string[]>((res, rej) => - generateKeyPair( - "rsa", - { - modulusLength: 4096, - publicKeyEncoding: { - type: "spki", - format: "pem", - }, - privateKeyEncoding: { - type: "pkcs8", - format: "pem", - cipher: undefined, - passphrase: undefined, - }, - } as any, - (err, publicKey, privateKey) => - err ? rej(err) : res([publicKey, privateKey]), - ), - ); - - let account!: User; - - // Start transaction - await db.transaction(async (transactionalEntityManager) => { - const exist = await transactionalEntityManager.findOneBy(User, { - usernameLower: username.toLowerCase(), - host: IsNull(), - }); - - if (exist) throw new Error(" the username is already used"); - - account = await transactionalEntityManager.save( - new User({ - id: genId(), - createdAt: new Date(), - username: username, - usernameLower: username.toLowerCase(), - host: toPunyNullable(host), - token: secret, - isAdmin: - (await Users.countBy({ - host: IsNull(), - isAdmin: true, - })) === 0, - }), - ); - - await transactionalEntityManager.save( - new UserKeypair({ - publicKey: keyPair[0], - privateKey: keyPair[1], - userId: account.id, - }), - ); - - await transactionalEntityManager.save( - new UserProfile({ - userId: account.id, - autoAcceptFollowed: true, - password: hash, - }), - ); - - await transactionalEntityManager.save( - new UsedUsername({ - createdAt: new Date(), - username: username.toLowerCase(), - }), - ); - }); - - usersChart.update(account, true); - - return { account, secret }; -} diff --git a/packages/backend/src/server/api/compatibility.ts b/packages/backend/src/server/api/compatibility.ts deleted file mode 100644 index 7e44fa8b2e..0000000000 --- a/packages/backend/src/server/api/compatibility.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { IEndpoint } from "./endpoints"; - -import * as cp___instanceInfo from "./endpoints/compatibility/instance-info.js"; -import * as cp___customEmojis from "./endpoints/compatibility/custom-emojis.js"; - -const cps = [ - ["v1/instance", cp___instanceInfo], - ["v1/custom_emojis", cp___customEmojis], -]; - -const compatibility: IEndpoint[] = cps.map(([name, cp]) => { - return { - name: name, - exec: cp.default, - meta: cp.meta || {}, - params: cp.paramDef, - } as IEndpoint; -}); - -export default compatibility; diff --git a/packages/backend/src/server/api/define.ts b/packages/backend/src/server/api/define.ts deleted file mode 100644 index ee0844185f..0000000000 --- a/packages/backend/src/server/api/define.ts +++ /dev/null @@ -1,105 +0,0 @@ -import * as fs from "node:fs"; -import Ajv from "ajv"; -import type { CacheableLocalUser } from "@/models/entities/user.js"; -import { ILocalUser } from "@/models/entities/user.js"; -import type { Schema, SchemaType } from "@/misc/schema.js"; -import type { AccessToken } from "@/models/entities/access-token.js"; -import type { IEndpointMeta } from "./endpoints.js"; -import { ApiError } from "./error.js"; - -export type Response = Record<string, any> | void; - -// TODO: paramsの型をT['params']のスキーマ定義から推論する -type executor<T extends IEndpointMeta, Ps extends Schema> = ( - params: SchemaType<Ps>, - user: T["requireCredential"] extends true - ? CacheableLocalUser - : CacheableLocalUser | null, - token: AccessToken | null, - file?: any, - cleanup?: () => any, - ip?: string | null, - headers?: Record<string, string> | null, -) => Promise< - T["res"] extends undefined ? Response : SchemaType<NonNullable<T["res"]>> ->; - -const ajv = new Ajv({ - useDefaults: true, -}); - -ajv.addFormat("misskey:id", /^[a-zA-Z0-9]+$/); - -export default function <T extends IEndpointMeta, Ps extends Schema>( - meta: T, - paramDef: Ps, - cb: executor<T, Ps>, -): ( - params: any, - user: T["requireCredential"] extends true - ? CacheableLocalUser - : CacheableLocalUser | null, - token: AccessToken | null, - file?: any, - ip?: string | null, - headers?: Record<string, string> | null, -) => Promise<any> { - const validate = ajv.compile(paramDef); - - return ( - params: any, - user: T["requireCredential"] extends true - ? CacheableLocalUser - : CacheableLocalUser | null, - token: AccessToken | null, - file?: any, - ip?: string | null, - headers?: Record<string, string> | null, - ) => { - let cleanup: undefined | (() => void) = undefined; - - if (meta.requireFile) { - cleanup = () => { - fs.unlink(file.path, () => {}); - }; - - if (file == null) - return Promise.reject( - new ApiError({ - message: "File required.", - code: "FILE_REQUIRED", - id: "4267801e-70d1-416a-b011-4ee502885d8b", - }), - ); - } - - const valid = validate(params); - if (!valid) { - if (file) cleanup!(); - - const errors = validate.errors!; - const err = new ApiError( - { - message: "Invalid param.", - code: "INVALID_PARAM", - id: "3d81ceae-475f-4600-b2a8-2bc116157532", - }, - { - param: errors[0].schemaPath, - reason: errors[0].message, - }, - ); - return Promise.reject(err); - } - - return cb( - params as SchemaType<Ps>, - user, - token, - file, - cleanup, - ip, - headers, - ); - }; -} diff --git a/packages/backend/src/server/api/endpoints.ts b/packages/backend/src/server/api/endpoints.ts deleted file mode 100644 index 3f82eb7a73..0000000000 --- a/packages/backend/src/server/api/endpoints.ts +++ /dev/null @@ -1,805 +0,0 @@ -import type { Schema } from "@/misc/schema.js"; - -import * as ep___admin_meta from "./endpoints/admin/meta.js"; -import * as ep___admin_abuseUserReports from "./endpoints/admin/abuse-user-reports.js"; -import * as ep___admin_accounts_create from "./endpoints/admin/accounts/create.js"; -import * as ep___admin_accounts_delete from "./endpoints/admin/accounts/delete.js"; -import * as ep___admin_accounts_hosted from "./endpoints/admin/accounts/hosted.js"; -import * as ep___admin_ad_create from "./endpoints/admin/ad/create.js"; -import * as ep___admin_ad_delete from "./endpoints/admin/ad/delete.js"; -import * as ep___admin_ad_list from "./endpoints/admin/ad/list.js"; -import * as ep___admin_ad_update from "./endpoints/admin/ad/update.js"; -import * as ep___admin_announcements_create from "./endpoints/admin/announcements/create.js"; -import * as ep___admin_announcements_delete from "./endpoints/admin/announcements/delete.js"; -import * as ep___admin_announcements_list from "./endpoints/admin/announcements/list.js"; -import * as ep___admin_announcements_update from "./endpoints/admin/announcements/update.js"; -import * as ep___admin_deleteAllFilesOfAUser from "./endpoints/admin/delete-all-files-of-a-user.js"; -import * as ep___admin_drive_cleanRemoteFiles from "./endpoints/admin/drive/clean-remote-files.js"; -import * as ep___admin_drive_cleanup from "./endpoints/admin/drive/cleanup.js"; -import * as ep___admin_drive_files from "./endpoints/admin/drive/files.js"; -import * as ep___admin_drive_showFile from "./endpoints/admin/drive/show-file.js"; -import * as ep___admin_emoji_addAliasesBulk from "./endpoints/admin/emoji/add-aliases-bulk.js"; -import * as ep___admin_emoji_add from "./endpoints/admin/emoji/add.js"; -import * as ep___admin_emoji_copy from "./endpoints/admin/emoji/copy.js"; -import * as ep___admin_emoji_deleteBulk from "./endpoints/admin/emoji/delete-bulk.js"; -import * as ep___admin_emoji_delete from "./endpoints/admin/emoji/delete.js"; -import * as ep___admin_emoji_importZip from "./endpoints/admin/emoji/import-zip.js"; -import * as ep___admin_emoji_listRemote from "./endpoints/admin/emoji/list-remote.js"; -import * as ep___admin_emoji_list from "./endpoints/admin/emoji/list.js"; -import * as ep___admin_emoji_removeAliasesBulk from "./endpoints/admin/emoji/remove-aliases-bulk.js"; -import * as ep___admin_emoji_setAliasesBulk from "./endpoints/admin/emoji/set-aliases-bulk.js"; -import * as ep___admin_emoji_setCategoryBulk from "./endpoints/admin/emoji/set-category-bulk.js"; -import * as ep___admin_emoji_setLicenseBulk from "./endpoints/admin/emoji/set-license-bulk.js"; -import * as ep___admin_emoji_update from "./endpoints/admin/emoji/update.js"; -import * as ep___admin_federation_deleteAllFiles from "./endpoints/admin/federation/delete-all-files.js"; -import * as ep___admin_federation_refreshRemoteInstanceMetadata from "./endpoints/admin/federation/refresh-remote-instance-metadata.js"; -import * as ep___admin_federation_removeAllFollowing from "./endpoints/admin/federation/remove-all-following.js"; -import * as ep___admin_federation_updateInstance from "./endpoints/admin/federation/update-instance.js"; -import * as ep___admin_getIndexStats from "./endpoints/admin/get-index-stats.js"; -import * as ep___admin_getTableStats from "./endpoints/admin/get-table-stats.js"; -import * as ep___admin_getUserIps from "./endpoints/admin/get-user-ips.js"; -import * as ep___admin_invite from "./endpoints/admin/invite.js"; -import * as ep___admin_moderators_add from "./endpoints/admin/moderators/add.js"; -import * as ep___admin_moderators_remove from "./endpoints/admin/moderators/remove.js"; -import * as ep___admin_promo_create from "./endpoints/admin/promo/create.js"; -import * as ep___admin_queue_clear from "./endpoints/admin/queue/clear.js"; -import * as ep___admin_queue_deliverDelayed from "./endpoints/admin/queue/deliver-delayed.js"; -import * as ep___admin_queue_inboxDelayed from "./endpoints/admin/queue/inbox-delayed.js"; -import * as ep___admin_queue_stats from "./endpoints/admin/queue/stats.js"; -import * as ep___admin_relays_add from "./endpoints/admin/relays/add.js"; -import * as ep___admin_relays_list from "./endpoints/admin/relays/list.js"; -import * as ep___admin_relays_remove from "./endpoints/admin/relays/remove.js"; -import * as ep___admin_resetPassword from "./endpoints/admin/reset-password.js"; -import * as ep___admin_resolveAbuseUserReport from "./endpoints/admin/resolve-abuse-user-report.js"; -import * as ep___admin_search_indexAll from "./endpoints/admin/search/index-all.js"; -import * as ep___admin_sendEmail from "./endpoints/admin/send-email.js"; -import * as ep___admin_serverInfo from "./endpoints/admin/server-info.js"; -import * as ep___admin_showModerationLogs from "./endpoints/admin/show-moderation-logs.js"; -import * as ep___admin_showUser from "./endpoints/admin/show-user.js"; -import * as ep___admin_showUsers from "./endpoints/admin/show-users.js"; -import * as ep___admin_silenceUser from "./endpoints/admin/silence-user.js"; -import * as ep___admin_suspendUser from "./endpoints/admin/suspend-user.js"; -import * as ep___admin_unsilenceUser from "./endpoints/admin/unsilence-user.js"; -import * as ep___admin_unsuspendUser from "./endpoints/admin/unsuspend-user.js"; -import * as ep___admin_updateMeta from "./endpoints/admin/update-meta.js"; -import * as ep___admin_vacuum from "./endpoints/admin/vacuum.js"; -import * as ep___admin_deleteAccount from "./endpoints/admin/delete-account.js"; -import * as ep___admin_updateUserNote from "./endpoints/admin/update-user-note.js"; -import * as ep___announcements from "./endpoints/announcements.js"; -import * as ep___antennas_create from "./endpoints/antennas/create.js"; -import * as ep___antennas_delete from "./endpoints/antennas/delete.js"; -import * as ep___antennas_list from "./endpoints/antennas/list.js"; -import * as ep___antennas_markRead from "./endpoints/antennas/markread.js"; -import * as ep___antennas_notes from "./endpoints/antennas/notes.js"; -import * as ep___antennas_show from "./endpoints/antennas/show.js"; -import * as ep___antennas_update from "./endpoints/antennas/update.js"; -import * as ep___ap_get from "./endpoints/ap/get.js"; -import * as ep___ap_show from "./endpoints/ap/show.js"; -import * as ep___app_create from "./endpoints/app/create.js"; -import * as ep___app_show from "./endpoints/app/show.js"; -import * as ep___auth_accept from "./endpoints/auth/accept.js"; -import * as ep___auth_session_generate from "./endpoints/auth/session/generate.js"; -import * as ep___auth_session_show from "./endpoints/auth/session/show.js"; -import * as ep___auth_session_userkey from "./endpoints/auth/session/userkey.js"; -import * as ep___blocking_create from "./endpoints/blocking/create.js"; -import * as ep___blocking_delete from "./endpoints/blocking/delete.js"; -import * as ep___blocking_list from "./endpoints/blocking/list.js"; -import * as ep___channels_create from "./endpoints/channels/create.js"; -import * as ep___channels_featured from "./endpoints/channels/featured.js"; -import * as ep___channels_follow from "./endpoints/channels/follow.js"; -import * as ep___channels_followed from "./endpoints/channels/followed.js"; -import * as ep___channels_owned from "./endpoints/channels/owned.js"; -import * as ep___channels_show from "./endpoints/channels/show.js"; -import * as ep___channels_timeline from "./endpoints/channels/timeline.js"; -import * as ep___channels_unfollow from "./endpoints/channels/unfollow.js"; -import * as ep___channels_update from "./endpoints/channels/update.js"; -import * as ep___charts_activeUsers from "./endpoints/charts/active-users.js"; -import * as ep___charts_apRequest from "./endpoints/charts/ap-request.js"; -import * as ep___charts_drive from "./endpoints/charts/drive.js"; -import * as ep___charts_federation from "./endpoints/charts/federation.js"; -import * as ep___charts_hashtag from "./endpoints/charts/hashtag.js"; -import * as ep___charts_instance from "./endpoints/charts/instance.js"; -import * as ep___charts_notes from "./endpoints/charts/notes.js"; -import * as ep___charts_user_drive from "./endpoints/charts/user/drive.js"; -import * as ep___charts_user_following from "./endpoints/charts/user/following.js"; -import * as ep___charts_user_notes from "./endpoints/charts/user/notes.js"; -import * as ep___charts_user_reactions from "./endpoints/charts/user/reactions.js"; -import * as ep___charts_users from "./endpoints/charts/users.js"; -import * as ep___clips_addNote from "./endpoints/clips/add-note.js"; -import * as ep___clips_removeNote from "./endpoints/clips/remove-note.js"; -import * as ep___clips_create from "./endpoints/clips/create.js"; -import * as ep___clips_delete from "./endpoints/clips/delete.js"; -import * as ep___clips_list from "./endpoints/clips/list.js"; -import * as ep___clips_notes from "./endpoints/clips/notes.js"; -import * as ep___clips_show from "./endpoints/clips/show.js"; -import * as ep___clips_update from "./endpoints/clips/update.js"; -import * as ep___drive from "./endpoints/drive.js"; -import * as ep___drive_files from "./endpoints/drive/files.js"; -import * as ep___drive_files_attachedNotes from "./endpoints/drive/files/attached-notes.js"; -import * as ep___drive_files_checkExistence from "./endpoints/drive/files/check-existence.js"; -import * as ep___drive_files_captionImage from "./endpoints/drive/files/caption-image.js"; -import * as ep___drive_files_create from "./endpoints/drive/files/create.js"; -import * as ep___drive_files_delete from "./endpoints/drive/files/delete.js"; -import * as ep___drive_files_findByHash from "./endpoints/drive/files/find-by-hash.js"; -import * as ep___drive_files_find from "./endpoints/drive/files/find.js"; -import * as ep___drive_files_show from "./endpoints/drive/files/show.js"; -import * as ep___drive_files_update from "./endpoints/drive/files/update.js"; -import * as ep___drive_files_uploadFromUrl from "./endpoints/drive/files/upload-from-url.js"; -import * as ep___drive_folders from "./endpoints/drive/folders.js"; -import * as ep___drive_folders_create from "./endpoints/drive/folders/create.js"; -import * as ep___drive_folders_delete from "./endpoints/drive/folders/delete.js"; -import * as ep___drive_folders_find from "./endpoints/drive/folders/find.js"; -import * as ep___drive_folders_show from "./endpoints/drive/folders/show.js"; -import * as ep___drive_folders_update from "./endpoints/drive/folders/update.js"; -import * as ep___drive_stream from "./endpoints/drive/stream.js"; -import * as ep___emailAddress_available from "./endpoints/email-address/available.js"; -import * as ep___emoji from "./endpoints/emoji.js"; -import * as ep___endpoint from "./endpoints/endpoint.js"; -import * as ep___endpoints from "./endpoints/endpoints.js"; -import * as ep___exportCustomEmojis from "./endpoints/export-custom-emojis.js"; -import * as ep___federation_followers from "./endpoints/federation/followers.js"; -import * as ep___federation_following from "./endpoints/federation/following.js"; -import * as ep___federation_instances from "./endpoints/federation/instances.js"; -import * as ep___federation_showInstance from "./endpoints/federation/show-instance.js"; -import * as ep___federation_updateRemoteUser from "./endpoints/federation/update-remote-user.js"; -import * as ep___federation_users from "./endpoints/federation/users.js"; -import * as ep___federation_stats from "./endpoints/federation/stats.js"; -import * as ep___following_create from "./endpoints/following/create.js"; -import * as ep___following_delete from "./endpoints/following/delete.js"; -import * as ep___following_invalidate from "./endpoints/following/invalidate.js"; -import * as ep___following_requests_accept from "./endpoints/following/requests/accept.js"; -import * as ep___following_requests_cancel from "./endpoints/following/requests/cancel.js"; -import * as ep___following_requests_list from "./endpoints/following/requests/list.js"; -import * as ep___following_requests_reject from "./endpoints/following/requests/reject.js"; -import * as ep___gallery_featured from "./endpoints/gallery/featured.js"; -import * as ep___gallery_popular from "./endpoints/gallery/popular.js"; -import * as ep___gallery_posts from "./endpoints/gallery/posts.js"; -import * as ep___gallery_posts_create from "./endpoints/gallery/posts/create.js"; -import * as ep___gallery_posts_delete from "./endpoints/gallery/posts/delete.js"; -import * as ep___gallery_posts_like from "./endpoints/gallery/posts/like.js"; -import * as ep___gallery_posts_show from "./endpoints/gallery/posts/show.js"; -import * as ep___gallery_posts_unlike from "./endpoints/gallery/posts/unlike.js"; -import * as ep___gallery_posts_update from "./endpoints/gallery/posts/update.js"; -import * as ep___getOnlineUsersCount from "./endpoints/get-online-users-count.js"; -import * as ep___hashtags_list from "./endpoints/hashtags/list.js"; -import * as ep___hashtags_search from "./endpoints/hashtags/search.js"; -import * as ep___hashtags_show from "./endpoints/hashtags/show.js"; -import * as ep___hashtags_trend from "./endpoints/hashtags/trend.js"; -import * as ep___hashtags_users from "./endpoints/hashtags/users.js"; -import * as ep___i from "./endpoints/i.js"; -import * as ep___i_2fa_done from "./endpoints/i/2fa/done.js"; -import * as ep___i_2fa_keyDone from "./endpoints/i/2fa/key-done.js"; -import * as ep___i_2fa_passwordLess from "./endpoints/i/2fa/password-less.js"; -import * as ep___i_2fa_registerKey from "./endpoints/i/2fa/register-key.js"; -import * as ep___i_2fa_register from "./endpoints/i/2fa/register.js"; -import * as ep___i_2fa_removeKey from "./endpoints/i/2fa/remove-key.js"; -import * as ep___i_2fa_unregister from "./endpoints/i/2fa/unregister.js"; -import * as ep___i_apps from "./endpoints/i/apps.js"; -import * as ep___i_authorizedApps from "./endpoints/i/authorized-apps.js"; -import * as ep___i_changePassword from "./endpoints/i/change-password.js"; -import * as ep___i_deleteAccount from "./endpoints/i/delete-account.js"; -import * as ep___i_exportBlocking from "./endpoints/i/export-blocking.js"; -import * as ep___i_exportFollowing from "./endpoints/i/export-following.js"; -import * as ep___i_exportMute from "./endpoints/i/export-mute.js"; -import * as ep___i_exportNotes from "./endpoints/i/export-notes.js"; -import * as ep___i_importPosts from "./endpoints/i/import-posts.js"; -import * as ep___i_exportUserLists from "./endpoints/i/export-user-lists.js"; -import * as ep___i_favorites from "./endpoints/i/favorites.js"; -import * as ep___i_gallery_likes from "./endpoints/i/gallery/likes.js"; -import * as ep___i_gallery_posts from "./endpoints/i/gallery/posts.js"; -import * as ep___i_getWordMutedNotesCount from "./endpoints/i/get-word-muted-notes-count.js"; -import * as ep___i_importBlocking from "./endpoints/i/import-blocking.js"; -import * as ep___i_importFollowing from "./endpoints/i/import-following.js"; -import * as ep___i_importMuting from "./endpoints/i/import-muting.js"; -import * as ep___i_importUserLists from "./endpoints/i/import-user-lists.js"; -import * as ep___i_notifications from "./endpoints/i/notifications.js"; -import * as ep___i_pageLikes from "./endpoints/i/page-likes.js"; -import * as ep___i_pages from "./endpoints/i/pages.js"; -import * as ep___i_pin from "./endpoints/i/pin.js"; -import * as ep___i_readAllMessagingMessages from "./endpoints/i/read-all-messaging-messages.js"; -import * as ep___i_readAllUnreadNotes from "./endpoints/i/read-all-unread-notes.js"; -import * as ep___i_readAnnouncement from "./endpoints/i/read-announcement.js"; -import * as ep___i_regenerateToken from "./endpoints/i/regenerate-token.js"; -import * as ep___i_registry_getAll from "./endpoints/i/registry/get-all.js"; -import * as ep___i_registry_getDetail from "./endpoints/i/registry/get-detail.js"; -import * as ep___i_registry_getUnsecure from "./endpoints/i/registry/get-unsecure.js"; -import * as ep___i_registry_get from "./endpoints/i/registry/get.js"; -import * as ep___i_registry_keysWithType from "./endpoints/i/registry/keys-with-type.js"; -import * as ep___i_registry_keys from "./endpoints/i/registry/keys.js"; -import * as ep___i_registry_remove from "./endpoints/i/registry/remove.js"; -import * as ep___i_registry_scopes from "./endpoints/i/registry/scopes.js"; -import * as ep___i_registry_set from "./endpoints/i/registry/set.js"; -import * as ep___i_revokeToken from "./endpoints/i/revoke-token.js"; -import * as ep___i_signinHistory from "./endpoints/i/signin-history.js"; -import * as ep___i_unpin from "./endpoints/i/unpin.js"; -import * as ep___i_updateEmail from "./endpoints/i/update-email.js"; -import * as ep___i_update from "./endpoints/i/update.js"; -import * as ep___i_userGroupInvites from "./endpoints/i/user-group-invites.js"; -import * as ep___i_webhooks_create from "./endpoints/i/webhooks/create.js"; -import * as ep___i_webhooks_show from "./endpoints/i/webhooks/show.js"; -import * as ep___i_webhooks_list from "./endpoints/i/webhooks/list.js"; -import * as ep___i_webhooks_update from "./endpoints/i/webhooks/update.js"; -import * as ep___i_webhooks_delete from "./endpoints/i/webhooks/delete.js"; -import * as ep___messaging_history from "./endpoints/messaging/history.js"; -import * as ep___messaging_messages from "./endpoints/messaging/messages.js"; -import * as ep___messaging_messages_create from "./endpoints/messaging/messages/create.js"; -import * as ep___messaging_messages_delete from "./endpoints/messaging/messages/delete.js"; -import * as ep___messaging_messages_read from "./endpoints/messaging/messages/read.js"; -import * as ep___meta from "./endpoints/meta.js"; -import * as ep___sounds from "./endpoints/get-sounds.js"; -import * as ep___miauth_genToken from "./endpoints/miauth/gen-token.js"; -import * as ep___mute_create from "./endpoints/mute/create.js"; -import * as ep___mute_delete from "./endpoints/mute/delete.js"; -import * as ep___mute_list from "./endpoints/mute/list.js"; -import * as ep___renote_mute_create from "./endpoints/renote-mute/create.js"; -import * as ep___renote_mute_delete from "./endpoints/renote-mute/delete.js"; -import * as ep___renote_mute_list from "./endpoints/renote-mute/list.js"; -import * as ep___my_apps from "./endpoints/my/apps.js"; -import * as ep___notes from "./endpoints/notes.js"; -import * as ep___notes_children from "./endpoints/notes/children.js"; -import * as ep___notes_clips from "./endpoints/notes/clips.js"; -import * as ep___notes_conversation from "./endpoints/notes/conversation.js"; -import * as ep___notes_create from "./endpoints/notes/create.js"; -import * as ep___notes_delete from "./endpoints/notes/delete.js"; -import * as ep___notes_favorites_create from "./endpoints/notes/favorites/create.js"; -import * as ep___notes_favorites_delete from "./endpoints/notes/favorites/delete.js"; -import * as ep___notes_featured from "./endpoints/notes/featured.js"; -import * as ep___notes_globalTimeline from "./endpoints/notes/global-timeline.js"; -import * as ep___notes_hybridTimeline from "./endpoints/notes/hybrid-timeline.js"; -import * as ep___notes_localTimeline from "./endpoints/notes/local-timeline.js"; -import * as ep___notes_recommendedTimeline from "./endpoints/notes/recommended-timeline.js"; -import * as ep___notes_mentions from "./endpoints/notes/mentions.js"; -import * as ep___notes_polls_recommendation from "./endpoints/notes/polls/recommendation.js"; -import * as ep___notes_polls_vote from "./endpoints/notes/polls/vote.js"; -import * as ep___notes_reactions from "./endpoints/notes/reactions.js"; -import * as ep___notes_reactions_create from "./endpoints/notes/reactions/create.js"; -import * as ep___notes_reactions_delete from "./endpoints/notes/reactions/delete.js"; -import * as ep___notes_renotes from "./endpoints/notes/renotes.js"; -import * as ep___notes_replies from "./endpoints/notes/replies.js"; -import * as ep___notes_searchByTag from "./endpoints/notes/search-by-tag.js"; -import * as ep___notes_search from "./endpoints/notes/search.js"; -import * as ep___notes_show from "./endpoints/notes/show.js"; -import * as ep___notes_state from "./endpoints/notes/state.js"; -import * as ep___notes_threadMuting_create from "./endpoints/notes/thread-muting/create.js"; -import * as ep___notes_threadMuting_delete from "./endpoints/notes/thread-muting/delete.js"; -import * as ep___notes_timeline from "./endpoints/notes/timeline.js"; -import * as ep___notes_translate from "./endpoints/notes/translate.js"; -import * as ep___notes_unrenote from "./endpoints/notes/unrenote.js"; -import * as ep___notes_userListTimeline from "./endpoints/notes/user-list-timeline.js"; -import * as ep___notes_watching_create from "./endpoints/notes/watching/create.js"; -import * as ep___notes_watching_delete from "./endpoints/notes/watching/delete.js"; -import * as ep___notifications_create from "./endpoints/notifications/create.js"; -import * as ep___notifications_markAllAsRead from "./endpoints/notifications/mark-all-as-read.js"; -import * as ep___notifications_read from "./endpoints/notifications/read.js"; -import * as ep___pagePush from "./endpoints/page-push.js"; -import * as ep___pages_create from "./endpoints/pages/create.js"; -import * as ep___pages_delete from "./endpoints/pages/delete.js"; -import * as ep___pages_featured from "./endpoints/pages/featured.js"; -import * as ep___pages_like from "./endpoints/pages/like.js"; -import * as ep___pages_show from "./endpoints/pages/show.js"; -import * as ep___pages_unlike from "./endpoints/pages/unlike.js"; -import * as ep___pages_update from "./endpoints/pages/update.js"; -import * as ep___ping from "./endpoints/ping.js"; -import * as ep___recommendedInstances from "./endpoints/recommended-instances.js"; -import * as ep___pinnedUsers from "./endpoints/pinned-users.js"; -import * as ep___customMOTD from "./endpoints/custom-motd.js"; -import * as ep___customSplashIcons from "./endpoints/custom-splash-icons.js"; -import * as ep___latestVersion from "./endpoints/latest-version.js"; -import * as ep___patrons from "./endpoints/patrons.js"; -import * as ep___release from "./endpoints/release.js"; -import * as ep___promo_read from "./endpoints/promo/read.js"; -import * as ep___requestResetPassword from "./endpoints/request-reset-password.js"; -import * as ep___resetDb from "./endpoints/reset-db.js"; -import * as ep___resetPassword from "./endpoints/reset-password.js"; -import * as ep___serverInfo from "./endpoints/server-info.js"; -import * as ep___stats from "./endpoints/stats.js"; -import * as ep___sw_show_registration from "./endpoints/sw/show-registration.js"; -import * as ep___sw_update_registration from "./endpoints/sw/update-registration.js"; -import * as ep___sw_register from "./endpoints/sw/register.js"; -import * as ep___sw_unregister from "./endpoints/sw/unregister.js"; -import * as ep___test from "./endpoints/test.js"; -import * as ep___username_available from "./endpoints/username/available.js"; -import * as ep___users from "./endpoints/users.js"; -import * as ep___users_clips from "./endpoints/users/clips.js"; -import * as ep___users_followers from "./endpoints/users/followers.js"; -import * as ep___users_following from "./endpoints/users/following.js"; -import * as ep___users_gallery_posts from "./endpoints/users/gallery/posts.js"; -import * as ep___users_getFrequentlyRepliedUsers from "./endpoints/users/get-frequently-replied-users.js"; -import * as ep___users_groups_create from "./endpoints/users/groups/create.js"; -import * as ep___users_groups_delete from "./endpoints/users/groups/delete.js"; -import * as ep___users_groups_invitations_accept from "./endpoints/users/groups/invitations/accept.js"; -import * as ep___users_groups_invitations_reject from "./endpoints/users/groups/invitations/reject.js"; -import * as ep___users_groups_invite from "./endpoints/users/groups/invite.js"; -import * as ep___users_groups_joined from "./endpoints/users/groups/joined.js"; -import * as ep___users_groups_leave from "./endpoints/users/groups/leave.js"; -import * as ep___users_groups_owned from "./endpoints/users/groups/owned.js"; -import * as ep___users_groups_pull from "./endpoints/users/groups/pull.js"; -import * as ep___users_groups_show from "./endpoints/users/groups/show.js"; -import * as ep___users_groups_transfer from "./endpoints/users/groups/transfer.js"; -import * as ep___users_groups_update from "./endpoints/users/groups/update.js"; -import * as ep___users_lists_create from "./endpoints/users/lists/create.js"; -import * as ep___users_lists_delete from "./endpoints/users/lists/delete.js"; -import * as ep___users_lists_delete_all from "./endpoints/users/lists/delete-all.js"; -import * as ep___users_lists_list from "./endpoints/users/lists/list.js"; -import * as ep___users_lists_pull from "./endpoints/users/lists/pull.js"; -import * as ep___users_lists_push from "./endpoints/users/lists/push.js"; -import * as ep___users_lists_show from "./endpoints/users/lists/show.js"; -import * as ep___users_lists_update from "./endpoints/users/lists/update.js"; -import * as ep___users_notes from "./endpoints/users/notes.js"; -import * as ep___users_pages from "./endpoints/users/pages.js"; -import * as ep___users_reactions from "./endpoints/users/reactions.js"; -import * as ep___users_recommendation from "./endpoints/users/recommendation.js"; -import * as ep___users_relation from "./endpoints/users/relation.js"; -import * as ep___users_reportAbuse from "./endpoints/users/report-abuse.js"; -import * as ep___users_searchByUsernameAndHost from "./endpoints/users/search-by-username-and-host.js"; -import * as ep___users_search from "./endpoints/users/search.js"; -import * as ep___users_show from "./endpoints/users/show.js"; -import * as ep___users_stats from "./endpoints/users/stats.js"; -import * as ep___fetchRss from "./endpoints/fetch-rss.js"; -import * as ep___admin_driveCapOverride from "./endpoints/admin/drive-capacity-override.js"; - -//Calckey Move -import * as ep___i_move from "./endpoints/i/move.js"; -import * as ep___i_known_as from "./endpoints/i/known-as.js"; - -const eps = [ - ["admin/meta", ep___admin_meta], - ["admin/abuse-user-reports", ep___admin_abuseUserReports], - ["admin/accounts/create", ep___admin_accounts_create], - ["admin/accounts/delete", ep___admin_accounts_delete], - ["admin/accounts/hosted", ep___admin_accounts_hosted], - ["admin/ad/create", ep___admin_ad_create], - ["admin/ad/delete", ep___admin_ad_delete], - ["admin/ad/list", ep___admin_ad_list], - ["admin/ad/update", ep___admin_ad_update], - ["admin/announcements/create", ep___admin_announcements_create], - ["admin/announcements/delete", ep___admin_announcements_delete], - ["admin/announcements/list", ep___admin_announcements_list], - ["admin/announcements/update", ep___admin_announcements_update], - ["admin/delete-all-files-of-a-user", ep___admin_deleteAllFilesOfAUser], - ["admin/drive/clean-remote-files", ep___admin_drive_cleanRemoteFiles], - ["admin/drive/cleanup", ep___admin_drive_cleanup], - ["admin/drive/files", ep___admin_drive_files], - ["admin/drive/show-file", ep___admin_drive_showFile], - ["admin/emoji/add-aliases-bulk", ep___admin_emoji_addAliasesBulk], - ["admin/emoji/add", ep___admin_emoji_add], - ["admin/emoji/copy", ep___admin_emoji_copy], - ["admin/emoji/delete-bulk", ep___admin_emoji_deleteBulk], - ["admin/emoji/delete", ep___admin_emoji_delete], - ["admin/emoji/import-zip", ep___admin_emoji_importZip], - ["admin/emoji/list-remote", ep___admin_emoji_listRemote], - ["admin/emoji/list", ep___admin_emoji_list], - ["admin/emoji/remove-aliases-bulk", ep___admin_emoji_removeAliasesBulk], - ["admin/emoji/set-aliases-bulk", ep___admin_emoji_setAliasesBulk], - ["admin/emoji/set-category-bulk", ep___admin_emoji_setCategoryBulk], - ["admin/emoji/set-license-bulk", ep___admin_emoji_setLicenseBulk], - ["admin/emoji/update", ep___admin_emoji_update], - ["admin/federation/delete-all-files", ep___admin_federation_deleteAllFiles], - [ - "admin/federation/refresh-remote-instance-metadata", - ep___admin_federation_refreshRemoteInstanceMetadata, - ], - [ - "admin/federation/remove-all-following", - ep___admin_federation_removeAllFollowing, - ], - ["admin/federation/update-instance", ep___admin_federation_updateInstance], - ["admin/get-index-stats", ep___admin_getIndexStats], - ["admin/get-table-stats", ep___admin_getTableStats], - ["admin/get-user-ips", ep___admin_getUserIps], - ["admin/invite", ep___admin_invite], - ["admin/moderators/add", ep___admin_moderators_add], - ["admin/moderators/remove", ep___admin_moderators_remove], - ["admin/promo/create", ep___admin_promo_create], - ["admin/queue/clear", ep___admin_queue_clear], - ["admin/queue/deliver-delayed", ep___admin_queue_deliverDelayed], - ["admin/queue/inbox-delayed", ep___admin_queue_inboxDelayed], - ["admin/queue/stats", ep___admin_queue_stats], - ["admin/relays/add", ep___admin_relays_add], - ["admin/relays/list", ep___admin_relays_list], - ["admin/relays/remove", ep___admin_relays_remove], - ["admin/reset-password", ep___admin_resetPassword], - ["admin/resolve-abuse-user-report", ep___admin_resolveAbuseUserReport], - ["admin/search/index-all", ep___admin_search_indexAll], - ["admin/send-email", ep___admin_sendEmail], - ["admin/server-info", ep___admin_serverInfo], - ["admin/show-moderation-logs", ep___admin_showModerationLogs], - ["admin/show-user", ep___admin_showUser], - ["admin/show-users", ep___admin_showUsers], - ["admin/silence-user", ep___admin_silenceUser], - ["admin/suspend-user", ep___admin_suspendUser], - ["admin/unsilence-user", ep___admin_unsilenceUser], - ["admin/unsuspend-user", ep___admin_unsuspendUser], - ["admin/update-meta", ep___admin_updateMeta], - ["admin/vacuum", ep___admin_vacuum], - ["admin/delete-account", ep___admin_deleteAccount], - ["admin/update-user-note", ep___admin_updateUserNote], - ["announcements", ep___announcements], - ["antennas/create", ep___antennas_create], - ["antennas/delete", ep___antennas_delete], - ["antennas/list", ep___antennas_list], - ["antennas/mark-read", ep___antennas_markRead], - ["antennas/notes", ep___antennas_notes], - ["antennas/show", ep___antennas_show], - ["antennas/update", ep___antennas_update], - ["ap/get", ep___ap_get], - ["ap/show", ep___ap_show], - ["app/create", ep___app_create], - ["app/show", ep___app_show], - ["auth/accept", ep___auth_accept], - ["auth/session/generate", ep___auth_session_generate], - ["auth/session/show", ep___auth_session_show], - ["auth/session/userkey", ep___auth_session_userkey], - ["blocking/create", ep___blocking_create], - ["blocking/delete", ep___blocking_delete], - ["blocking/list", ep___blocking_list], - ["channels/create", ep___channels_create], - ["channels/featured", ep___channels_featured], - ["channels/follow", ep___channels_follow], - ["channels/followed", ep___channels_followed], - ["channels/owned", ep___channels_owned], - ["channels/show", ep___channels_show], - ["channels/timeline", ep___channels_timeline], - ["channels/unfollow", ep___channels_unfollow], - ["channels/update", ep___channels_update], - ["charts/active-users", ep___charts_activeUsers], - ["charts/ap-request", ep___charts_apRequest], - ["charts/drive", ep___charts_drive], - ["charts/federation", ep___charts_federation], - ["charts/hashtag", ep___charts_hashtag], - ["charts/instance", ep___charts_instance], - ["charts/notes", ep___charts_notes], - ["charts/user/drive", ep___charts_user_drive], - ["charts/user/following", ep___charts_user_following], - ["charts/user/notes", ep___charts_user_notes], - ["charts/user/reactions", ep___charts_user_reactions], - ["charts/users", ep___charts_users], - ["clips/add-note", ep___clips_addNote], - ["clips/remove-note", ep___clips_removeNote], - ["clips/create", ep___clips_create], - ["clips/delete", ep___clips_delete], - ["clips/list", ep___clips_list], - ["clips/notes", ep___clips_notes], - ["clips/show", ep___clips_show], - ["clips/update", ep___clips_update], - ["drive", ep___drive], - ["drive/files", ep___drive_files], - ["drive/files/attached-notes", ep___drive_files_attachedNotes], - ["drive/files/caption-image", ep___drive_files_captionImage], - ["drive/files/check-existence", ep___drive_files_checkExistence], - ["drive/files/create", ep___drive_files_create], - ["drive/files/delete", ep___drive_files_delete], - ["drive/files/find-by-hash", ep___drive_files_findByHash], - ["drive/files/find", ep___drive_files_find], - ["drive/files/show", ep___drive_files_show], - ["drive/files/update", ep___drive_files_update], - ["drive/files/upload-from-url", ep___drive_files_uploadFromUrl], - ["drive/folders", ep___drive_folders], - ["drive/folders/create", ep___drive_folders_create], - ["drive/folders/delete", ep___drive_folders_delete], - ["drive/folders/find", ep___drive_folders_find], - ["drive/folders/show", ep___drive_folders_show], - ["drive/folders/update", ep___drive_folders_update], - ["drive/stream", ep___drive_stream], - ["email-address/available", ep___emailAddress_available], - ["emoji", ep___emoji], - ["endpoint", ep___endpoint], - ["endpoints", ep___endpoints], - ["export-custom-emojis", ep___exportCustomEmojis], - ["federation/followers", ep___federation_followers], - ["federation/following", ep___federation_following], - ["federation/instances", ep___federation_instances], - ["federation/show-instance", ep___federation_showInstance], - ["federation/update-remote-user", ep___federation_updateRemoteUser], - ["federation/users", ep___federation_users], - ["federation/stats", ep___federation_stats], - ["following/create", ep___following_create], - ["following/delete", ep___following_delete], - ["following/invalidate", ep___following_invalidate], - ["following/requests/accept", ep___following_requests_accept], - ["following/requests/cancel", ep___following_requests_cancel], - ["following/requests/list", ep___following_requests_list], - ["following/requests/reject", ep___following_requests_reject], - ["gallery/featured", ep___gallery_featured], - ["gallery/popular", ep___gallery_popular], - ["gallery/posts", ep___gallery_posts], - ["gallery/posts/create", ep___gallery_posts_create], - ["gallery/posts/delete", ep___gallery_posts_delete], - ["gallery/posts/like", ep___gallery_posts_like], - ["gallery/posts/show", ep___gallery_posts_show], - ["gallery/posts/unlike", ep___gallery_posts_unlike], - ["gallery/posts/update", ep___gallery_posts_update], - ["get-online-users-count", ep___getOnlineUsersCount], - ["hashtags/list", ep___hashtags_list], - ["hashtags/search", ep___hashtags_search], - ["hashtags/show", ep___hashtags_show], - ["hashtags/trend", ep___hashtags_trend], - ["hashtags/users", ep___hashtags_users], - ["i", ep___i], - ["i/known-as", ep___i_known_as], - ["i/move", ep___i_move], - ["i/2fa/done", ep___i_2fa_done], - ["i/2fa/key-done", ep___i_2fa_keyDone], - ["i/2fa/password-less", ep___i_2fa_passwordLess], - ["i/2fa/register-key", ep___i_2fa_registerKey], - ["i/2fa/register", ep___i_2fa_register], - ["i/2fa/remove-key", ep___i_2fa_removeKey], - ["i/2fa/unregister", ep___i_2fa_unregister], - ["i/apps", ep___i_apps], - ["i/authorized-apps", ep___i_authorizedApps], - ["i/change-password", ep___i_changePassword], - ["i/delete-account", ep___i_deleteAccount], - ["i/export-blocking", ep___i_exportBlocking], - ["i/export-following", ep___i_exportFollowing], - ["i/export-mute", ep___i_exportMute], - ["i/export-notes", ep___i_exportNotes], - ["i/import-posts", ep___i_importPosts], - ["i/export-user-lists", ep___i_exportUserLists], - ["i/favorites", ep___i_favorites], - ["i/gallery/likes", ep___i_gallery_likes], - ["i/gallery/posts", ep___i_gallery_posts], - ["i/get-word-muted-notes-count", ep___i_getWordMutedNotesCount], - ["i/import-blocking", ep___i_importBlocking], - ["i/import-following", ep___i_importFollowing], - ["i/import-muting", ep___i_importMuting], - ["i/import-user-lists", ep___i_importUserLists], - ["i/notifications", ep___i_notifications], - ["i/page-likes", ep___i_pageLikes], - ["i/pages", ep___i_pages], - ["i/pin", ep___i_pin], - ["i/read-all-messaging-messages", ep___i_readAllMessagingMessages], - ["i/read-all-unread-notes", ep___i_readAllUnreadNotes], - ["i/read-announcement", ep___i_readAnnouncement], - ["i/regenerate-token", ep___i_regenerateToken], - ["i/registry/get-all", ep___i_registry_getAll], - ["i/registry/get-detail", ep___i_registry_getDetail], - ["i/registry/get-unsecure", ep___i_registry_getUnsecure], - ["i/registry/get", ep___i_registry_get], - ["i/registry/keys-with-type", ep___i_registry_keysWithType], - ["i/registry/keys", ep___i_registry_keys], - ["i/registry/remove", ep___i_registry_remove], - ["i/registry/scopes", ep___i_registry_scopes], - ["i/registry/set", ep___i_registry_set], - ["i/revoke-token", ep___i_revokeToken], - ["i/signin-history", ep___i_signinHistory], - ["i/unpin", ep___i_unpin], - ["i/update-email", ep___i_updateEmail], - ["i/update", ep___i_update], - ["i/user-group-invites", ep___i_userGroupInvites], - ["i/webhooks/create", ep___i_webhooks_create], - ["i/webhooks/list", ep___i_webhooks_list], - ["i/webhooks/show", ep___i_webhooks_show], - ["i/webhooks/update", ep___i_webhooks_update], - ["i/webhooks/delete", ep___i_webhooks_delete], - ["messaging/history", ep___messaging_history], - ["messaging/messages", ep___messaging_messages], - ["messaging/messages/create", ep___messaging_messages_create], - ["messaging/messages/delete", ep___messaging_messages_delete], - ["messaging/messages/read", ep___messaging_messages_read], - ["meta", ep___meta], - ["miauth/gen-token", ep___miauth_genToken], - ["mute/create", ep___mute_create], - ["mute/delete", ep___mute_delete], - ["mute/list", ep___mute_list], - ["my/apps", ep___my_apps], - ["notes", ep___notes], - ["notes/children", ep___notes_children], - ["notes/clips", ep___notes_clips], - ["notes/conversation", ep___notes_conversation], - ["notes/create", ep___notes_create], - ["notes/delete", ep___notes_delete], - ["notes/favorites/create", ep___notes_favorites_create], - ["notes/favorites/delete", ep___notes_favorites_delete], - ["notes/featured", ep___notes_featured], - ["notes/global-timeline", ep___notes_globalTimeline], - ["notes/hybrid-timeline", ep___notes_hybridTimeline], - ["notes/local-timeline", ep___notes_localTimeline], - ["notes/recommended-timeline", ep___notes_recommendedTimeline], - ["notes/mentions", ep___notes_mentions], - ["notes/polls/recommendation", ep___notes_polls_recommendation], - ["notes/polls/vote", ep___notes_polls_vote], - ["notes/reactions", ep___notes_reactions], - ["notes/reactions/create", ep___notes_reactions_create], - ["notes/reactions/delete", ep___notes_reactions_delete], - ["notes/renotes", ep___notes_renotes], - ["notes/replies", ep___notes_replies], - ["notes/search-by-tag", ep___notes_searchByTag], - ["notes/search", ep___notes_search], - ["notes/show", ep___notes_show], - ["notes/state", ep___notes_state], - ["notes/thread-muting/create", ep___notes_threadMuting_create], - ["notes/thread-muting/delete", ep___notes_threadMuting_delete], - ["notes/timeline", ep___notes_timeline], - ["notes/translate", ep___notes_translate], - ["notes/unrenote", ep___notes_unrenote], - ["notes/user-list-timeline", ep___notes_userListTimeline], - ["notes/watching/create", ep___notes_watching_create], - ["notes/watching/delete", ep___notes_watching_delete], - ["notifications/create", ep___notifications_create], - ["notifications/mark-all-as-read", ep___notifications_markAllAsRead], - ["notifications/read", ep___notifications_read], - ["page-push", ep___pagePush], - ["pages/create", ep___pages_create], - ["pages/delete", ep___pages_delete], - ["pages/featured", ep___pages_featured], - ["pages/like", ep___pages_like], - ["pages/show", ep___pages_show], - ["pages/unlike", ep___pages_unlike], - ["pages/update", ep___pages_update], - ["ping", ep___ping], - ["pinned-users", ep___pinnedUsers], - ["recommended-instances", ep___recommendedInstances], - ["renote-mute/create", ep___renote_mute_create], - ["renote-mute/delete", ep___renote_mute_delete], - ["renote-mute/list", ep___renote_mute_list], - ["custom-motd", ep___customMOTD], - ["custom-splash-icons", ep___customSplashIcons], - ["latest-version", ep___latestVersion], - ["patrons", ep___patrons], - ["release", ep___release], - ["promo/read", ep___promo_read], - ["request-reset-password", ep___requestResetPassword], - ["reset-db", ep___resetDb], - ["reset-password", ep___resetPassword], - ["server-info", ep___serverInfo], - ["stats", ep___stats], - ["sw/register", ep___sw_register], - ["sw/unregister", ep___sw_unregister], - ["sw/show-registration", ep___sw_show_registration], - ["sw/update-registration", ep___sw_update_registration], - ["test", ep___test], - ["username/available", ep___username_available], - ["users", ep___users], - ["users/clips", ep___users_clips], - ["users/followers", ep___users_followers], - ["users/following", ep___users_following], - ["users/gallery/posts", ep___users_gallery_posts], - ["users/get-frequently-replied-users", ep___users_getFrequentlyRepliedUsers], - ["users/groups/create", ep___users_groups_create], - ["users/groups/delete", ep___users_groups_delete], - ["users/groups/invitations/accept", ep___users_groups_invitations_accept], - ["users/groups/invitations/reject", ep___users_groups_invitations_reject], - ["users/groups/invite", ep___users_groups_invite], - ["users/groups/joined", ep___users_groups_joined], - ["users/groups/leave", ep___users_groups_leave], - ["users/groups/owned", ep___users_groups_owned], - ["users/groups/pull", ep___users_groups_pull], - ["users/groups/show", ep___users_groups_show], - ["users/groups/transfer", ep___users_groups_transfer], - ["users/groups/update", ep___users_groups_update], - ["users/lists/create", ep___users_lists_create], - ["users/lists/delete", ep___users_lists_delete], - ["users/lists/delete-all", ep___users_lists_delete_all], - ["users/lists/list", ep___users_lists_list], - ["users/lists/pull", ep___users_lists_pull], - ["users/lists/push", ep___users_lists_push], - ["users/lists/show", ep___users_lists_show], - ["users/lists/update", ep___users_lists_update], - ["users/notes", ep___users_notes], - ["users/pages", ep___users_pages], - ["users/reactions", ep___users_reactions], - ["users/recommendation", ep___users_recommendation], - ["users/relation", ep___users_relation], - ["users/report-abuse", ep___users_reportAbuse], - ["users/search-by-username-and-host", ep___users_searchByUsernameAndHost], - ["users/search", ep___users_search], - ["users/show", ep___users_show], - ["users/stats", ep___users_stats], - ["admin/drive-capacity-override", ep___admin_driveCapOverride], - ["fetch-rss", ep___fetchRss], - ["get-sounds", ep___sounds], -]; - -export interface IEndpointMeta { - readonly stability?: "deprecated" | "experimental" | "stable"; - - readonly tags?: ReadonlyArray<string>; - - readonly errors?: { - readonly [key: string]: { - readonly message: string; - readonly code: string; - readonly id: string; - }; - }; - - readonly res?: Schema; - - /** - * このエンドポイントにリクエストするのにユーザー情報が必須か否か - * 省略した場合は false として解釈されます。 - */ - readonly requireCredential?: boolean; - - /** - * 管理者のみ使えるエンドポイントか否か - */ - readonly requireAdmin?: boolean; - - /** - * 管理者またはモデレーターのみ使えるエンドポイントか否か - */ - readonly requireModerator?: boolean; - - /** - * エンドポイントのリミテーションに関するやつ - * 省略した場合はリミテーションは無いものとして解釈されます。 - */ - readonly limit?: { - /** - * 複数のエンドポイントでリミットを共有したい場合に指定するキー - */ - readonly key?: string; - - /** - * リミットを適用する期間(ms) - * このプロパティを設定する場合、max プロパティも設定する必要があります。 - */ - readonly duration?: number; - - /** - * durationで指定した期間内にいくつまでリクエストできるのか - * このプロパティを設定する場合、duration プロパティも設定する必要があります。 - */ - readonly max?: number; - - /** - * 最低でもどれくらいの間隔を開けてリクエストしなければならないか(ms) - */ - readonly minInterval?: number; - }; - - /** - * ファイルの添付を必要とするか否か - * 省略した場合は false として解釈されます。 - */ - readonly requireFile?: boolean; - - /** - * サードパーティアプリからはリクエストすることができないか否か - * 省略した場合は false として解釈されます。 - */ - readonly secure?: boolean; - - /** - * プライベートモードでなら、このエンドポイントにリクエストするときにユーザー情報が必要か否か - * 省略した場合は false として解釈されます - */ - readonly requireCredentialPrivateMode?: boolean; - - /** - * エンドポイントの種類 - * パーミッションの実現に利用されます。 - */ - readonly kind?: string; - - readonly description?: string; - - /** - * GETでのリクエストを許容するか否か - */ - readonly allowGet?: boolean; - - /** - * 正常応答をキャッシュ (Cache-Control: public) する秒数 - */ - readonly cacheSec?: number; -} - -export interface IEndpoint { - name: string; - exec: any; // TODO: may be obosolete @ThatOneCalculator - meta: IEndpointMeta; - params: Schema; -} - -const endpoints: IEndpoint[] = (eps as [string, any]).map(([name, ep]) => { - return { - name: name, - exec: ep.default, - meta: ep.meta ?? {}, - params: ep.paramDef, - }; -}); - -export default endpoints; diff --git a/packages/backend/src/server/api/endpoints/admin/abuse-user-reports.ts b/packages/backend/src/server/api/endpoints/admin/abuse-user-reports.ts deleted file mode 100644 index 4861431403..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/abuse-user-reports.ts +++ /dev/null @@ -1,144 +0,0 @@ -import define from "../../define.js"; -import { AbuseUserReports } from "@/models/index.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - nullable: false, - optional: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - nullable: false, - optional: false, - format: "date-time", - }, - comment: { - type: "string", - nullable: false, - optional: false, - }, - resolved: { - type: "boolean", - nullable: false, - optional: false, - example: false, - }, - reporterId: { - type: "string", - nullable: false, - optional: false, - format: "id", - }, - targetUserId: { - type: "string", - nullable: false, - optional: false, - format: "id", - }, - assigneeId: { - type: "string", - nullable: true, - optional: false, - format: "id", - }, - reporter: { - type: "object", - nullable: false, - optional: false, - ref: "User", - }, - targetUser: { - type: "object", - nullable: false, - optional: false, - ref: "User", - }, - assignee: { - type: "object", - nullable: true, - optional: true, - ref: "User", - }, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - state: { type: "string", nullable: true, default: null }, - reporterOrigin: { - type: "string", - enum: ["combined", "local", "remote"], - default: "combined", - }, - targetUserOrigin: { - type: "string", - enum: ["combined", "local", "remote"], - default: "combined", - }, - forwarded: { type: "boolean", default: false }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps) => { - const query = makePaginationQuery( - AbuseUserReports.createQueryBuilder("report"), - ps.sinceId, - ps.untilId, - ); - - switch (ps.state) { - case "resolved": - query.andWhere("report.resolved = TRUE"); - break; - case "unresolved": - query.andWhere("report.resolved = FALSE"); - break; - } - - switch (ps.reporterOrigin) { - case "local": - query.andWhere("report.reporterHost IS NULL"); - break; - case "remote": - query.andWhere("report.reporterHost IS NOT NULL"); - break; - } - - switch (ps.targetUserOrigin) { - case "local": - query.andWhere("report.targetUserHost IS NULL"); - break; - case "remote": - query.andWhere("report.targetUserHost IS NOT NULL"); - break; - } - - const reports = await query.take(ps.limit).getMany(); - - return await AbuseUserReports.packMany(reports); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/accounts/create.ts b/packages/backend/src/server/api/endpoints/admin/accounts/create.ts deleted file mode 100644 index 2e035d1695..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/accounts/create.ts +++ /dev/null @@ -1,55 +0,0 @@ -import define from "../../../define.js"; -import { Users } from "@/models/index.js"; -import { signup } from "../../../common/signup.js"; -import { IsNull } from "typeorm"; - -export const meta = { - tags: ["admin"], - - res: { - type: "object", - optional: false, - nullable: false, - ref: "User", - properties: { - token: { - type: "string", - optional: false, - nullable: false, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - username: Users.localUsernameSchema, - password: Users.passwordSchema, - }, - required: ["username", "password"], -} as const; - -export default define(meta, paramDef, async (ps, _me) => { - const me = _me ? await Users.findOneByOrFail({ id: _me.id }) : null; - const noUsers = - (await Users.countBy({ - host: IsNull(), - isAdmin: true, - })) === 0; - if (!(noUsers || me?.isAdmin)) throw new Error("access denied"); - - const { account, secret } = await signup({ - username: ps.username, - password: ps.password, - }); - - const res = await Users.pack(account, account, { - detail: true, - includeSecrets: true, - }); - - (res as any).token = secret; - - return res; -}); diff --git a/packages/backend/src/server/api/endpoints/admin/accounts/delete.ts b/packages/backend/src/server/api/endpoints/admin/accounts/delete.ts deleted file mode 100644 index 3f7243ab50..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/accounts/delete.ts +++ /dev/null @@ -1,58 +0,0 @@ -import define from "../../../define.js"; -import { Users } from "@/models/index.js"; -import { doPostSuspend } from "@/services/suspend-user.js"; -import { publishUserEvent } from "@/services/stream.js"; -import { createDeleteAccountJob } from "@/queue/index.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const user = await Users.findOneBy({ id: ps.userId }); - - if (user == null) { - throw new Error("user not found"); - } - - if (user.isAdmin) { - throw new Error("cannot suspend admin"); - } - - if (user.isModerator) { - throw new Error("cannot suspend moderator"); - } - - if (Users.isLocalUser(user)) { - // 物理削除する前にDelete activityを送信する - await doPostSuspend(user).catch((e) => {}); - - createDeleteAccountJob(user, { - soft: false, - }); - } else { - createDeleteAccountJob(user, { - soft: true, // リモートユーザーの削除は、完全にDBから物理削除してしまうと再度連合してきてアカウントが復活する可能性があるため、soft指定する - }); - } - - await Users.update(user.id, { - isDeleted: true, - }); - - if (Users.isLocalUser(user)) { - // Terminate streaming - publishUserEvent(user.id, "terminate", {}); - } -}); diff --git a/packages/backend/src/server/api/endpoints/admin/accounts/hosted.ts b/packages/backend/src/server/api/endpoints/admin/accounts/hosted.ts deleted file mode 100644 index 15ad1f9a17..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/accounts/hosted.ts +++ /dev/null @@ -1,116 +0,0 @@ -import config from "@/config/index.js"; -import { Meta } from "@/models/entities/meta.js"; -import { insertModerationLog } from "@/services/insert-moderation-log.js"; -import { db } from "@/db/postgre.js"; -import define from "../../../define.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireAdmin: true, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const hostedConfig = config.isManagedHosting; - const hosted = hostedConfig != null && hostedConfig === true; - if (hosted) { - const set = {} as Partial<Meta>; - if (config.deepl.managed != null && config.deepl.managed === true) { - if (typeof config.deepl.authKey === "boolean") { - set.deeplAuthKey = config.deepl.authKey; - } - if (typeof config.deepl.isPro === "boolean") { - set.deeplIsPro = config.deepl.isPro; - } - } - if (config.email.managed != null && config.email.managed === true) { - set.enableEmail = true; - if (typeof config.email.address === "string") { - set.email = config.email.address; - } - if (typeof config.email.host === "string") { - set.smtpHost = config.email.host; - } - if (typeof config.email.port === "number") { - set.smtpPort = config.email.port; - } - if (typeof config.email.user === "string") { - set.smtpUser = config.email.user; - } - if (typeof config.email.pass === "string") { - set.smtpPass = config.email.pass; - } - if (typeof config.email.useImplicitSslTls === "boolean") { - set.smtpSecure = config.email.useImplicitSslTls; - } - } - if ( - config.objectStorage.managed != null && - config.objectStorage.managed === true - ) { - set.useObjectStorage = true; - if (typeof config.objectStorage.baseUrl === "string") { - set.objectStorageBaseUrl = config.objectStorage.baseUrl; - } - if (typeof config.objectStorage.bucket === "string") { - set.objectStorageBucket = config.objectStorage.bucket; - } - if (typeof config.objectStorage.prefix === "string") { - set.objectStoragePrefix = config.objectStorage.prefix; - } - if (typeof config.objectStorage.endpoint === "string") { - set.objectStorageEndpoint = config.objectStorage.endpoint; - } - if (typeof config.objectStorage.region === "string") { - set.objectStorageRegion = config.objectStorage.region; - } - if (typeof config.objectStorage.accessKey === "string") { - set.objectStorageAccessKey = config.objectStorage.accessKey; - } - if (typeof config.objectStorage.secretKey === "string") { - set.objectStorageSecretKey = config.objectStorage.secretKey; - } - if (typeof config.objectStorage.useSsl === "boolean") { - set.objectStorageUseSSL = config.objectStorage.useSsl; - } - if (typeof config.objectStorage.connnectOverProxy === "boolean") { - set.objectStorageUseProxy = config.objectStorage.connnectOverProxy; - } - if (typeof config.objectStorage.setPublicReadOnUpload === "boolean") { - set.objectStorageSetPublicRead = - config.objectStorage.setPublicReadOnUpload; - } - if (typeof config.objectStorage.s3ForcePathStyle === "boolean") { - set.objectStorageS3ForcePathStyle = - config.objectStorage.s3ForcePathStyle; - } - } - if (config.summalyProxyUrl !== undefined) { - set.summalyProxy = config.summalyProxyUrl; - } - await db.transaction(async (transactionalEntityManager) => { - const metas = await transactionalEntityManager.find(Meta, { - order: { - id: "DESC", - }, - }); - - const meta = metas[0]; - - if (meta) { - await transactionalEntityManager.update(Meta, meta.id, set); - } else { - await transactionalEntityManager.save(Meta, set); - } - }); - insertModerationLog(me, "updateMeta"); - } - return hosted; -}); diff --git a/packages/backend/src/server/api/endpoints/admin/ad/create.ts b/packages/backend/src/server/api/endpoints/admin/ad/create.ts deleted file mode 100644 index db39f3eb27..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/ad/create.ts +++ /dev/null @@ -1,46 +0,0 @@ -import define from "../../../define.js"; -import { Ads } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - url: { type: "string", minLength: 1 }, - memo: { type: "string" }, - place: { type: "string" }, - priority: { type: "string" }, - ratio: { type: "integer" }, - expiresAt: { type: "integer" }, - imageUrl: { type: "string", minLength: 1 }, - }, - required: [ - "url", - "memo", - "place", - "priority", - "ratio", - "expiresAt", - "imageUrl", - ], -} as const; - -export default define(meta, paramDef, async (ps) => { - await Ads.insert({ - id: genId(), - createdAt: new Date(), - expiresAt: new Date(ps.expiresAt), - url: ps.url, - imageUrl: ps.imageUrl, - priority: ps.priority, - ratio: ps.ratio, - place: ps.place, - memo: ps.memo, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/ad/delete.ts b/packages/backend/src/server/api/endpoints/admin/ad/delete.ts deleted file mode 100644 index ee6d314de7..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/ad/delete.ts +++ /dev/null @@ -1,34 +0,0 @@ -import define from "../../../define.js"; -import { Ads } from "@/models/index.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - errors: { - noSuchAd: { - message: "No such ad.", - code: "NO_SUCH_AD", - id: "ccac9863-3a03-416e-b899-8a64041118b1", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - id: { type: "string", format: "misskey:id" }, - }, - required: ["id"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const ad = await Ads.findOneBy({ id: ps.id }); - - if (ad == null) throw new ApiError(meta.errors.noSuchAd); - - await Ads.delete(ad.id); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/ad/list.ts b/packages/backend/src/server/api/endpoints/admin/ad/list.ts deleted file mode 100644 index 65944d31e9..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/ad/list.ts +++ /dev/null @@ -1,32 +0,0 @@ -import define from "../../../define.js"; -import { Ads } from "@/models/index.js"; -import { makePaginationQuery } from "../../../common/make-pagination-query.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps) => { - const query = makePaginationQuery( - Ads.createQueryBuilder("ad"), - ps.sinceId, - ps.untilId, - ).andWhere("ad.expiresAt > :now", { now: new Date() }); - - const ads = await query.take(ps.limit).getMany(); - - return ads; -}); diff --git a/packages/backend/src/server/api/endpoints/admin/ad/update.ts b/packages/backend/src/server/api/endpoints/admin/ad/update.ts deleted file mode 100644 index 2c70387310..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/ad/update.ts +++ /dev/null @@ -1,58 +0,0 @@ -import define from "../../../define.js"; -import { Ads } from "@/models/index.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - errors: { - noSuchAd: { - message: "No such ad.", - code: "NO_SUCH_AD", - id: "b7aa1727-1354-47bc-a182-3a9c3973d300", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - id: { type: "string", format: "misskey:id" }, - memo: { type: "string" }, - url: { type: "string", minLength: 1 }, - imageUrl: { type: "string", minLength: 1 }, - place: { type: "string" }, - priority: { type: "string" }, - ratio: { type: "integer" }, - expiresAt: { type: "integer" }, - }, - required: [ - "id", - "memo", - "url", - "imageUrl", - "place", - "priority", - "ratio", - "expiresAt", - ], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const ad = await Ads.findOneBy({ id: ps.id }); - - if (ad == null) throw new ApiError(meta.errors.noSuchAd); - - await Ads.update(ad.id, { - url: ps.url, - place: ps.place, - priority: ps.priority, - ratio: ps.ratio, - memo: ps.memo, - imageUrl: ps.imageUrl, - expiresAt: new Date(ps.expiresAt), - }); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/announcements/create.ts b/packages/backend/src/server/api/endpoints/admin/announcements/create.ts deleted file mode 100644 index a532b6677f..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/announcements/create.ts +++ /dev/null @@ -1,78 +0,0 @@ -import define from "../../../define.js"; -import { Announcements } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - updatedAt: { - type: "string", - optional: false, - nullable: true, - format: "date-time", - }, - title: { - type: "string", - optional: false, - nullable: false, - }, - text: { - type: "string", - optional: false, - nullable: false, - }, - imageUrl: { - type: "string", - optional: false, - nullable: true, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - title: { type: "string", minLength: 1 }, - text: { type: "string", minLength: 1 }, - imageUrl: { type: "string", nullable: true, minLength: 1 }, - }, - required: ["title", "text", "imageUrl"], -} as const; - -export default define(meta, paramDef, async (ps) => { - const announcement = await Announcements.insert({ - id: genId(), - createdAt: new Date(), - updatedAt: null, - title: ps.title, - text: ps.text, - imageUrl: ps.imageUrl, - }).then((x) => Announcements.findOneByOrFail(x.identifiers[0])); - - return Object.assign({}, announcement, { - createdAt: announcement.createdAt.toISOString(), - updatedAt: null, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/announcements/delete.ts b/packages/backend/src/server/api/endpoints/admin/announcements/delete.ts deleted file mode 100644 index 5665b94a7b..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/announcements/delete.ts +++ /dev/null @@ -1,34 +0,0 @@ -import define from "../../../define.js"; -import { Announcements } from "@/models/index.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - errors: { - noSuchAnnouncement: { - message: "No such announcement.", - code: "NO_SUCH_ANNOUNCEMENT", - id: "ecad8040-a276-4e85-bda9-015a708d291e", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - id: { type: "string", format: "misskey:id" }, - }, - required: ["id"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const announcement = await Announcements.findOneBy({ id: ps.id }); - - if (announcement == null) throw new ApiError(meta.errors.noSuchAnnouncement); - - await Announcements.delete(announcement.id); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/announcements/list.ts b/packages/backend/src/server/api/endpoints/admin/announcements/list.ts deleted file mode 100644 index fc5b020706..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/announcements/list.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { Announcements, AnnouncementReads } from "@/models/index.js"; -import type { Announcement } from "@/models/entities/announcement.js"; -import define from "../../../define.js"; -import { makePaginationQuery } from "../../../common/make-pagination-query.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - updatedAt: { - type: "string", - optional: false, - nullable: true, - format: "date-time", - }, - text: { - type: "string", - optional: false, - nullable: false, - }, - title: { - type: "string", - optional: false, - nullable: false, - }, - imageUrl: { - type: "string", - optional: false, - nullable: true, - }, - reads: { - type: "number", - optional: false, - nullable: false, - }, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps) => { - const query = makePaginationQuery( - Announcements.createQueryBuilder("announcement"), - ps.sinceId, - ps.untilId, - ); - - const announcements = await query.take(ps.limit).getMany(); - - const reads = new Map<Announcement, number>(); - - for (const announcement of announcements) { - reads.set( - announcement, - await AnnouncementReads.countBy({ - announcementId: announcement.id, - }), - ); - } - - return announcements.map((announcement) => ({ - id: announcement.id, - createdAt: announcement.createdAt.toISOString(), - updatedAt: announcement.updatedAt?.toISOString() ?? null, - title: announcement.title, - text: announcement.text, - imageUrl: announcement.imageUrl, - reads: reads.get(announcement)!, - })); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/announcements/update.ts b/packages/backend/src/server/api/endpoints/admin/announcements/update.ts deleted file mode 100644 index 35e64f2819..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/announcements/update.ts +++ /dev/null @@ -1,42 +0,0 @@ -import define from "../../../define.js"; -import { Announcements } from "@/models/index.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - errors: { - noSuchAnnouncement: { - message: "No such announcement.", - code: "NO_SUCH_ANNOUNCEMENT", - id: "d3aae5a7-6372-4cb4-b61c-f511ffc2d7cc", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - id: { type: "string", format: "misskey:id" }, - title: { type: "string", minLength: 1 }, - text: { type: "string", minLength: 1 }, - imageUrl: { type: "string", nullable: true, minLength: 1 }, - }, - required: ["id", "title", "text", "imageUrl"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const announcement = await Announcements.findOneBy({ id: ps.id }); - - if (announcement == null) throw new ApiError(meta.errors.noSuchAnnouncement); - - await Announcements.update(announcement.id, { - updatedAt: new Date(), - title: ps.title, - text: ps.text, - imageUrl: ps.imageUrl, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/delete-account.ts b/packages/backend/src/server/api/endpoints/admin/delete-account.ts deleted file mode 100644 index 9fd196888d..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/delete-account.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { Users } from "@/models/index.js"; -import { deleteAccount } from "@/services/delete-account.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireAdmin: true, - - res: {}, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps) => { - const user = await Users.findOneByOrFail({ id: ps.userId }); - if (user.isDeleted) { - return; - } - - await deleteAccount(user); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/delete-all-files-of-a-user.ts b/packages/backend/src/server/api/endpoints/admin/delete-all-files-of-a-user.ts deleted file mode 100644 index 7969008113..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/delete-all-files-of-a-user.ts +++ /dev/null @@ -1,28 +0,0 @@ -import define from "../../define.js"; -import { deleteFile } from "@/services/drive/delete-file.js"; -import { DriveFiles } from "@/models/index.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const files = await DriveFiles.findBy({ - userId: ps.userId, - }); - - for (const file of files) { - deleteFile(file); - } -}); diff --git a/packages/backend/src/server/api/endpoints/admin/drive-capacity-override.ts b/packages/backend/src/server/api/endpoints/admin/drive-capacity-override.ts deleted file mode 100644 index c8be344696..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/drive-capacity-override.ts +++ /dev/null @@ -1,43 +0,0 @@ -import define from "../../define.js"; -import { Users } from "@/models/index.js"; -import { insertModerationLog } from "@/services/insert-moderation-log.js"; -import { publishInternalEvent } from "@/services/stream.js"; -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - overrideMb: { type: "number", nullable: true }, - }, - required: ["userId", "overrideMb"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const user = await Users.findOneBy({ id: ps.userId }); - - if (user == null) { - throw new Error("user not found"); - } - - if (!Users.isLocalUser(user)) { - throw new Error("user is not local user"); - } - - await Users.update(user.id, { - driveCapacityOverrideMb: ps.overrideMb, - }); - - publishInternalEvent("localUserUpdated", { - id: user.id, - }); - - insertModerationLog(me, "change-drive-capacity-override", { - targetId: user.id, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/drive/clean-remote-files.ts b/packages/backend/src/server/api/endpoints/admin/drive/clean-remote-files.ts deleted file mode 100644 index 1b0c1260bd..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/drive/clean-remote-files.ts +++ /dev/null @@ -1,19 +0,0 @@ -import define from "../../../define.js"; -import { createCleanRemoteFilesJob } from "@/queue/index.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - createCleanRemoteFilesJob(); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/drive/cleanup.ts b/packages/backend/src/server/api/endpoints/admin/drive/cleanup.ts deleted file mode 100644 index 04208f6004..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/drive/cleanup.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { IsNull } from "typeorm"; -import define from "../../../define.js"; -import { deleteFile } from "@/services/drive/delete-file.js"; -import { DriveFiles } from "@/models/index.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const files = await DriveFiles.findBy({ - userId: IsNull(), - }); - - for (const file of files) { - deleteFile(file); - } -}); diff --git a/packages/backend/src/server/api/endpoints/admin/drive/files.ts b/packages/backend/src/server/api/endpoints/admin/drive/files.ts deleted file mode 100644 index 5cb0aecd81..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/drive/files.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { DriveFiles } from "@/models/index.js"; -import define from "../../../define.js"; -import { makePaginationQuery } from "../../../common/make-pagination-query.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: false, - requireModerator: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "DriveFile", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - userId: { type: "string", format: "misskey:id", nullable: true }, - type: { - type: "string", - nullable: true, - pattern: /^[a-zA-Z0-9\/\-*]+$/.toString().slice(1, -1), - }, - origin: { - type: "string", - enum: ["combined", "local", "remote"], - default: "local", - }, - hostname: { - type: "string", - nullable: true, - default: null, - description: "The local host is represented with `null`.", - }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = makePaginationQuery( - DriveFiles.createQueryBuilder("file"), - ps.sinceId, - ps.untilId, - ); - - if (ps.userId) { - query.andWhere("file.userId = :userId", { userId: ps.userId }); - } else { - if (ps.origin === "local") { - query.andWhere("file.userHost IS NULL"); - } else if (ps.origin === "remote") { - query.andWhere("file.userHost IS NOT NULL"); - } - - if (ps.hostname) { - query.andWhere("file.userHost = :hostname", { hostname: ps.hostname }); - } - } - - if (ps.type) { - if (ps.type.endsWith("/*")) { - query.andWhere("file.type like :type", { - type: `${ps.type.replace("/*", "/")}%`, - }); - } else { - query.andWhere("file.type = :type", { type: ps.type }); - } - } - - const files = await query.take(ps.limit).getMany(); - - return await DriveFiles.packMany(files, { - detail: true, - withUser: true, - self: true, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/drive/show-file.ts b/packages/backend/src/server/api/endpoints/admin/drive/show-file.ts deleted file mode 100644 index d65ec09fc2..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/drive/show-file.ts +++ /dev/null @@ -1,225 +0,0 @@ -import { DriveFiles } from "@/models/index.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - errors: { - noSuchFile: { - message: "No such file.", - code: "NO_SUCH_FILE", - id: "caf3ca38-c6e5-472e-a30c-b05377dcc240", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - userId: { - type: "string", - optional: false, - nullable: true, - format: "id", - example: "xxxxxxxxxx", - }, - userHost: { - type: "string", - optional: false, - nullable: true, - description: "The local host is represented with `null`.", - }, - md5: { - type: "string", - optional: false, - nullable: false, - format: "md5", - example: "15eca7fba0480996e2245f5185bf39f2", - }, - name: { - type: "string", - optional: false, - nullable: false, - example: "lenna.jpg", - }, - type: { - type: "string", - optional: false, - nullable: false, - example: "image/jpeg", - }, - size: { - type: "number", - optional: false, - nullable: false, - example: 51469, - }, - comment: { - type: "string", - optional: false, - nullable: true, - }, - blurhash: { - type: "string", - optional: false, - nullable: true, - }, - properties: { - type: "object", - optional: false, - nullable: false, - properties: { - width: { - type: "number", - optional: false, - nullable: false, - example: 1280, - }, - height: { - type: "number", - optional: false, - nullable: false, - example: 720, - }, - avgColor: { - type: "string", - optional: true, - nullable: false, - example: "rgb(40,65,87)", - }, - }, - }, - storedInternal: { - type: "boolean", - optional: false, - nullable: true, - example: true, - }, - url: { - type: "string", - optional: false, - nullable: true, - format: "url", - }, - thumbnailUrl: { - type: "string", - optional: false, - nullable: true, - format: "url", - }, - webpublicUrl: { - type: "string", - optional: false, - nullable: true, - format: "url", - }, - accessKey: { - type: "string", - optional: false, - nullable: false, - }, - thumbnailAccessKey: { - type: "string", - optional: false, - nullable: false, - }, - webpublicAccessKey: { - type: "string", - optional: false, - nullable: false, - }, - uri: { - type: "string", - optional: false, - nullable: true, - }, - src: { - type: "string", - optional: false, - nullable: true, - }, - folderId: { - type: "string", - optional: false, - nullable: true, - format: "id", - example: "xxxxxxxxxx", - }, - isSensitive: { - type: "boolean", - optional: false, - nullable: false, - }, - isLink: { - type: "boolean", - optional: false, - nullable: false, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - anyOf: [ - { - properties: { - fileId: { type: "string", format: "misskey:id" }, - }, - required: ["fileId"], - }, - { - properties: { - url: { type: "string" }, - }, - required: ["url"], - }, - ], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const file = ps.fileId - ? await DriveFiles.findOneBy({ id: ps.fileId }) - : await DriveFiles.findOne({ - where: [ - { - url: ps.url, - }, - { - thumbnailUrl: ps.url, - }, - { - webpublicUrl: ps.url, - }, - ], - }); - - if (file == null) { - throw new ApiError(meta.errors.noSuchFile); - } - - if (!me.isAdmin) { - file.requestIp = undefined; - file.requestHeaders = undefined; - } - - return file; -}); diff --git a/packages/backend/src/server/api/endpoints/admin/emoji/add-aliases-bulk.ts b/packages/backend/src/server/api/endpoints/admin/emoji/add-aliases-bulk.ts deleted file mode 100644 index 1ea457adf2..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/emoji/add-aliases-bulk.ts +++ /dev/null @@ -1,47 +0,0 @@ -import define from "../../../define.js"; -import { Emojis } from "@/models/index.js"; -import { In } from "typeorm"; -import { ApiError } from "../../../error.js"; -import { db } from "@/db/postgre.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - ids: { - type: "array", - items: { - type: "string", - format: "misskey:id", - }, - }, - aliases: { - type: "array", - items: { - type: "string", - }, - }, - }, - required: ["ids", "aliases"], -} as const; - -export default define(meta, paramDef, async (ps) => { - const emojis = await Emojis.findBy({ - id: In(ps.ids), - }); - - for (const emoji of emojis) { - await Emojis.update(emoji.id, { - updatedAt: new Date(), - aliases: [...new Set(emoji.aliases.concat(ps.aliases))], - }); - } - - await db.queryResultCache!.remove(["meta_emojis"]); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/emoji/add.ts b/packages/backend/src/server/api/endpoints/admin/emoji/add.ts deleted file mode 100644 index bfc025834f..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/emoji/add.ts +++ /dev/null @@ -1,68 +0,0 @@ -import define from "../../../define.js"; -import { Emojis, DriveFiles } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import { insertModerationLog } from "@/services/insert-moderation-log.js"; -import { ApiError } from "../../../error.js"; -import rndstr from "rndstr"; -import { publishBroadcastStream } from "@/services/stream.js"; -import { db } from "@/db/postgre.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - errors: { - noSuchFile: { - message: "No such file.", - code: "MO_SUCH_FILE", - id: "fc46b5a4-6b92-4c33-ac66-b806659bb5cf", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - fileId: { type: "string", format: "misskey:id" }, - }, - required: ["fileId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const file = await DriveFiles.findOneBy({ id: ps.fileId }); - - if (file == null) throw new ApiError(meta.errors.noSuchFile); - - const name = file.name.split(".")[0].match(/^[a-z0-9_]+$/) - ? file.name.split(".")[0] - : `_${rndstr("a-z0-9", 8)}_`; - - const emoji = await Emojis.insert({ - id: genId(), - updatedAt: new Date(), - name: name, - category: null, - host: null, - aliases: [], - originalUrl: file.url, - publicUrl: file.webpublicUrl ?? file.url, - type: file.webpublicType ?? file.type, - license: null, - }).then((x) => Emojis.findOneByOrFail(x.identifiers[0])); - - await db.queryResultCache!.remove(["meta_emojis"]); - - publishBroadcastStream("emojiAdded", { - emoji: await Emojis.pack(emoji.id), - }); - - insertModerationLog(me, "addEmoji", { - emojiId: emoji.id, - }); - - return { - id: emoji.id, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/admin/emoji/copy.ts b/packages/backend/src/server/api/endpoints/admin/emoji/copy.ts deleted file mode 100644 index 951158f7d4..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/emoji/copy.ts +++ /dev/null @@ -1,88 +0,0 @@ -import define from "../../../define.js"; -import { Emojis } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import { ApiError } from "../../../error.js"; -import type { DriveFile } from "@/models/entities/drive-file.js"; -import { uploadFromUrl } from "@/services/drive/upload-from-url.js"; -import { publishBroadcastStream } from "@/services/stream.js"; -import { db } from "@/db/postgre.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - errors: { - noSuchEmoji: { - message: "No such emoji.", - code: "NO_SUCH_EMOJI", - id: "e2785b66-dca3-4087-9cac-b93c541cc425", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - emojiId: { type: "string", format: "misskey:id" }, - }, - required: ["emojiId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const emoji = await Emojis.findOneBy({ id: ps.emojiId }); - - if (emoji == null) { - throw new ApiError(meta.errors.noSuchEmoji); - } - - let driveFile: DriveFile; - - try { - // Create file - driveFile = await uploadFromUrl({ - url: emoji.originalUrl, - user: null, - force: true, - }); - } catch (e) { - throw new ApiError(); - } - - const copied = await Emojis.insert({ - id: genId(), - updatedAt: new Date(), - name: emoji.name, - host: null, - aliases: [], - originalUrl: driveFile.url, - publicUrl: driveFile.webpublicUrl ?? driveFile.url, - type: driveFile.webpublicType ?? driveFile.type, - license: emoji.license, - }).then((x) => Emojis.findOneByOrFail(x.identifiers[0])); - - await db.queryResultCache!.remove(["meta_emojis"]); - - publishBroadcastStream("emojiAdded", { - emoji: await Emojis.pack(copied.id), - }); - - return { - id: copied.id, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/admin/emoji/delete-bulk.ts b/packages/backend/src/server/api/endpoints/admin/emoji/delete-bulk.ts deleted file mode 100644 index 585af231f6..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/emoji/delete-bulk.ts +++ /dev/null @@ -1,43 +0,0 @@ -import define from "../../../define.js"; -import { Emojis } from "@/models/index.js"; -import { In } from "typeorm"; -import { insertModerationLog } from "@/services/insert-moderation-log.js"; -import { ApiError } from "../../../error.js"; -import { db } from "@/db/postgre.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - ids: { - type: "array", - items: { - type: "string", - format: "misskey:id", - }, - }, - }, - required: ["ids"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const emojis = await Emojis.findBy({ - id: In(ps.ids), - }); - - for (const emoji of emojis) { - await Emojis.delete(emoji.id); - - await db.queryResultCache!.remove(["meta_emojis"]); - - insertModerationLog(me, "deleteEmoji", { - emoji: emoji, - }); - } -}); diff --git a/packages/backend/src/server/api/endpoints/admin/emoji/delete.ts b/packages/backend/src/server/api/endpoints/admin/emoji/delete.ts deleted file mode 100644 index 761c7c3776..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/emoji/delete.ts +++ /dev/null @@ -1,42 +0,0 @@ -import define from "../../../define.js"; -import { Emojis } from "@/models/index.js"; -import { insertModerationLog } from "@/services/insert-moderation-log.js"; -import { ApiError } from "../../../error.js"; -import { db } from "@/db/postgre.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - errors: { - noSuchEmoji: { - message: "No such emoji.", - code: "NO_SUCH_EMOJI", - id: "be83669b-773a-44b7-b1f8-e5e5170ac3c2", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - id: { type: "string", format: "misskey:id" }, - }, - required: ["id"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const emoji = await Emojis.findOneBy({ id: ps.id }); - - if (emoji == null) throw new ApiError(meta.errors.noSuchEmoji); - - await Emojis.delete(emoji.id); - - await db.queryResultCache!.remove(["meta_emojis"]); - - insertModerationLog(me, "deleteEmoji", { - emoji: emoji, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/emoji/import-zip.ts b/packages/backend/src/server/api/endpoints/admin/emoji/import-zip.ts deleted file mode 100644 index 6f49d6d18d..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/emoji/import-zip.ts +++ /dev/null @@ -1,21 +0,0 @@ -import define from "../../../define.js"; -import { createImportCustomEmojisJob } from "@/queue/index.js"; -import ms from "ms"; - -export const meta = { - secure: true, - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - fileId: { type: "string", format: "misskey:id" }, - }, - required: ["fileId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - createImportCustomEmojisJob(user, ps.fileId); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/emoji/list-remote.ts b/packages/backend/src/server/api/endpoints/admin/emoji/list-remote.ts deleted file mode 100644 index fae986dd96..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/emoji/list-remote.ts +++ /dev/null @@ -1,105 +0,0 @@ -import define from "../../../define.js"; -import { Emojis } from "@/models/index.js"; -import { toPuny } from "@/misc/convert-host.js"; -import { makePaginationQuery } from "../../../common/make-pagination-query.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - aliases: { - type: "array", - optional: false, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - name: { - type: "string", - optional: false, - nullable: false, - }, - category: { - type: "string", - optional: false, - nullable: true, - }, - host: { - type: "string", - optional: false, - nullable: true, - description: "The local host is represented with `null`.", - }, - url: { - type: "string", - optional: false, - nullable: false, - }, - license: { - type: "string", - optional: false, - nullable: true, - }, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - query: { type: "string", nullable: true, default: null }, - host: { - type: "string", - nullable: true, - default: null, - description: "Use `null` to represent the local host.", - }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps) => { - const q = makePaginationQuery( - Emojis.createQueryBuilder("emoji"), - ps.sinceId, - ps.untilId, - ); - - if (ps.host == null) { - q.andWhere("emoji.host IS NOT NULL"); - } else { - q.andWhere("emoji.host = :host", { host: toPuny(ps.host) }); - } - - if (ps.query) { - q.andWhere("emoji.name like :query", { query: `%${ps.query}%` }); - } - - const emojis = await q.orderBy("emoji.id", "DESC").take(ps.limit).getMany(); - - return Emojis.packMany(emojis); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/emoji/list.ts b/packages/backend/src/server/api/endpoints/admin/emoji/list.ts deleted file mode 100644 index aa49f14803..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/emoji/list.ts +++ /dev/null @@ -1,107 +0,0 @@ -import define from "../../../define.js"; -import { Emojis } from "@/models/index.js"; -import { makePaginationQuery } from "../../../common/make-pagination-query.js"; -import type { Emoji } from "@/models/entities/emoji.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - aliases: { - type: "array", - optional: false, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - name: { - type: "string", - optional: false, - nullable: false, - }, - category: { - type: "string", - optional: false, - nullable: true, - }, - host: { - type: "null", - optional: false, - description: - "The local host is represented with `null`. The field exists for compatibility with other API endpoints that return files.", - }, - url: { - type: "string", - optional: false, - nullable: false, - }, - license: { - type: "string", - optional: false, - nullable: true, - }, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - query: { type: "string", nullable: true, default: null }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps) => { - const q = makePaginationQuery( - Emojis.createQueryBuilder("emoji"), - ps.sinceId, - ps.untilId, - ).andWhere("emoji.host IS NULL"); - - let emojis: Emoji[]; - - if (ps.query) { - //q.andWhere('emoji.name ILIKE :q', { q: `%${ps.query}%` }); - //const emojis = await q.take(ps.limit).getMany(); - - emojis = await q.getMany(); - - emojis = emojis.filter( - (emoji) => - emoji.name.includes(ps.query!) || - emoji.aliases.some((a) => a.includes(ps.query!)) || - emoji.category?.includes(ps.query!), - ); - - emojis.splice(ps.limit + 1); - } else { - emojis = await q.take(ps.limit).getMany(); - } - - return Emojis.packMany(emojis); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/emoji/remove-aliases-bulk.ts b/packages/backend/src/server/api/endpoints/admin/emoji/remove-aliases-bulk.ts deleted file mode 100644 index 4e57fa3dda..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/emoji/remove-aliases-bulk.ts +++ /dev/null @@ -1,47 +0,0 @@ -import define from "../../../define.js"; -import { Emojis } from "@/models/index.js"; -import { In } from "typeorm"; -import { ApiError } from "../../../error.js"; -import { db } from "@/db/postgre.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - ids: { - type: "array", - items: { - type: "string", - format: "misskey:id", - }, - }, - aliases: { - type: "array", - items: { - type: "string", - }, - }, - }, - required: ["ids", "aliases"], -} as const; - -export default define(meta, paramDef, async (ps) => { - const emojis = await Emojis.findBy({ - id: In(ps.ids), - }); - - for (const emoji of emojis) { - await Emojis.update(emoji.id, { - updatedAt: new Date(), - aliases: emoji.aliases.filter((x) => !ps.aliases.includes(x)), - }); - } - - await db.queryResultCache!.remove(["meta_emojis"]); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/emoji/set-aliases-bulk.ts b/packages/backend/src/server/api/endpoints/admin/emoji/set-aliases-bulk.ts deleted file mode 100644 index 1197f60779..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/emoji/set-aliases-bulk.ts +++ /dev/null @@ -1,46 +0,0 @@ -import define from "../../../define.js"; -import { Emojis } from "@/models/index.js"; -import { In } from "typeorm"; -import { ApiError } from "../../../error.js"; -import { db } from "@/db/postgre.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - ids: { - type: "array", - items: { - type: "string", - format: "misskey:id", - }, - }, - aliases: { - type: "array", - items: { - type: "string", - }, - }, - }, - required: ["ids", "aliases"], -} as const; - -export default define(meta, paramDef, async (ps) => { - await Emojis.update( - { - id: In(ps.ids), - }, - { - updatedAt: new Date(), - aliases: ps.aliases, - }, - ); - - await db.queryResultCache!.remove(["meta_emojis"]); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/emoji/set-category-bulk.ts b/packages/backend/src/server/api/endpoints/admin/emoji/set-category-bulk.ts deleted file mode 100644 index 17881a4454..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/emoji/set-category-bulk.ts +++ /dev/null @@ -1,45 +0,0 @@ -import define from "../../../define.js"; -import { Emojis } from "@/models/index.js"; -import { In } from "typeorm"; -import { ApiError } from "../../../error.js"; -import { db } from "@/db/postgre.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - ids: { - type: "array", - items: { - type: "string", - format: "misskey:id", - }, - }, - category: { - type: "string", - nullable: true, - description: "Use `null` to reset the category.", - }, - }, - required: ["ids"], -} as const; - -export default define(meta, paramDef, async (ps) => { - await Emojis.update( - { - id: In(ps.ids), - }, - { - updatedAt: new Date(), - category: ps.category, - }, - ); - - await db.queryResultCache!.remove(["meta_emojis"]); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/emoji/set-license-bulk.ts b/packages/backend/src/server/api/endpoints/admin/emoji/set-license-bulk.ts deleted file mode 100644 index c98ca03fae..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/emoji/set-license-bulk.ts +++ /dev/null @@ -1,45 +0,0 @@ -import define from "../../../define.js"; -import { Emojis } from "@/models/index.js"; -import { In } from "typeorm"; -import { ApiError } from "../../../error.js"; -import { db } from "@/db/postgre.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - ids: { - type: "array", - items: { - type: "string", - format: "misskey:id", - }, - }, - license: { - type: "string", - nullable: true, - description: "Use `null` to reset the license.", - }, - }, - required: ["ids"], -} as const; - -export default define(meta, paramDef, async (ps) => { - await Emojis.update( - { - id: In(ps.ids), - }, - { - updatedAt: new Date(), - license: ps.license, - }, - ); - - await db.queryResultCache!.remove(["meta_emojis"]); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/emoji/update.ts b/packages/backend/src/server/api/endpoints/admin/emoji/update.ts deleted file mode 100644 index 9e2e854760..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/emoji/update.ts +++ /dev/null @@ -1,59 +0,0 @@ -import define from "../../../define.js"; -import { Emojis } from "@/models/index.js"; -import { ApiError } from "../../../error.js"; -import { db } from "@/db/postgre.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - errors: { - noSuchEmoji: { - message: "No such emoji.", - code: "NO_SUCH_EMOJI", - id: "684dec9d-a8c2-4364-9aa8-456c49cb1dc8", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - id: { type: "string", format: "misskey:id" }, - name: { type: "string" }, - category: { - type: "string", - nullable: true, - description: "Use `null` to reset the category.", - }, - aliases: { - type: "array", - items: { - type: "string", - }, - }, - license: { - type: "string", - nullable: true, - }, - }, - required: ["id", "name", "aliases"], -} as const; - -export default define(meta, paramDef, async (ps) => { - const emoji = await Emojis.findOneBy({ id: ps.id }); - - if (emoji == null) throw new ApiError(meta.errors.noSuchEmoji); - - await Emojis.update(emoji.id, { - updatedAt: new Date(), - name: ps.name, - category: ps.category, - aliases: ps.aliases, - license: ps.license, - }); - - await db.queryResultCache!.remove(["meta_emojis"]); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/federation/delete-all-files.ts b/packages/backend/src/server/api/endpoints/admin/federation/delete-all-files.ts deleted file mode 100644 index 534f226c28..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/federation/delete-all-files.ts +++ /dev/null @@ -1,28 +0,0 @@ -import define from "../../../define.js"; -import { deleteFile } from "@/services/drive/delete-file.js"; -import { DriveFiles } from "@/models/index.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - host: { type: "string" }, - }, - required: ["host"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const files = await DriveFiles.findBy({ - userHost: ps.host, - }); - - for (const file of files) { - deleteFile(file); - } -}); diff --git a/packages/backend/src/server/api/endpoints/admin/federation/refresh-remote-instance-metadata.ts b/packages/backend/src/server/api/endpoints/admin/federation/refresh-remote-instance-metadata.ts deleted file mode 100644 index 9c7165593c..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/federation/refresh-remote-instance-metadata.ts +++ /dev/null @@ -1,29 +0,0 @@ -import define from "../../../define.js"; -import { Instances } from "@/models/index.js"; -import { toPuny } from "@/misc/convert-host.js"; -import { fetchInstanceMetadata } from "@/services/fetch-instance-metadata.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - host: { type: "string" }, - }, - required: ["host"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const instance = await Instances.findOneBy({ host: toPuny(ps.host) }); - - if (instance == null) { - throw new Error("instance not found"); - } - - fetchInstanceMetadata(instance, true); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/federation/remove-all-following.ts b/packages/backend/src/server/api/endpoints/admin/federation/remove-all-following.ts deleted file mode 100644 index a1ccf11af0..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/federation/remove-all-following.ts +++ /dev/null @@ -1,37 +0,0 @@ -import define from "../../../define.js"; -import deleteFollowing from "@/services/following/delete.js"; -import { Followings, Users } from "@/models/index.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - host: { type: "string" }, - }, - required: ["host"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const followings = await Followings.findBy({ - followerHost: ps.host, - }); - - const pairs = await Promise.all( - followings.map((f) => - Promise.all([ - Users.findOneByOrFail({ id: f.followerId }), - Users.findOneByOrFail({ id: f.followeeId }), - ]), - ), - ); - - for (const pair of pairs) { - deleteFollowing(pair[0], pair[1]); - } -}); diff --git a/packages/backend/src/server/api/endpoints/admin/federation/update-instance.ts b/packages/backend/src/server/api/endpoints/admin/federation/update-instance.ts deleted file mode 100644 index 016989b541..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/federation/update-instance.ts +++ /dev/null @@ -1,34 +0,0 @@ -import define from "../../../define.js"; -import { Instances } from "@/models/index.js"; -import { toPuny } from "@/misc/convert-host.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - host: { type: "string" }, - isSuspended: { type: "boolean" }, - }, - required: ["host", "isSuspended"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const instance = await Instances.findOneBy({ host: toPuny(ps.host) }); - - if (instance == null) { - throw new Error("instance not found"); - } - - Instances.update( - { host: toPuny(ps.host) }, - { - isSuspended: ps.isSuspended, - }, - ); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/get-index-stats.ts b/packages/backend/src/server/api/endpoints/admin/get-index-stats.ts deleted file mode 100644 index f39a369ecb..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/get-index-stats.ts +++ /dev/null @@ -1,27 +0,0 @@ -import define from "../../define.js"; -import { db } from "@/db/postgre.js"; - -export const meta = { - requireCredential: true, - requireModerator: true, - - tags: ["admin"], -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - const stats = await db.query("SELECT * FROM pg_indexes;").then((recs) => { - const res = [] as { tablename: string; indexname: string }[]; - for (const rec of recs) { - res.push(rec); - } - return res; - }); - - return stats; -}); diff --git a/packages/backend/src/server/api/endpoints/admin/get-table-stats.ts b/packages/backend/src/server/api/endpoints/admin/get-table-stats.ts deleted file mode 100644 index 25d07f327a..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/get-table-stats.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { db } from "@/db/postgre.js"; -import define from "../../define.js"; - -export const meta = { - requireCredential: true, - requireModerator: true, - - tags: ["admin"], - - res: { - type: "object", - optional: false, - nullable: false, - example: { - migrations: { - count: 66, - size: 32768, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - const sizes = await db - .query(` - SELECT relname AS "table", reltuples as "count", pg_total_relation_size(C.oid) AS "size" - FROM pg_class C LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace) - WHERE nspname NOT IN ('pg_catalog', 'information_schema') - AND C.relkind <> 'i' - AND nspname !~ '^pg_toast';`) - .then((recs) => { - const res = {} as Record<string, { count: number; size: number }>; - for (const rec of recs) { - res[rec.table] = { - count: parseInt(rec.count, 10), - size: parseInt(rec.size, 10), - }; - } - return res; - }); - - return sizes; -}); diff --git a/packages/backend/src/server/api/endpoints/admin/get-user-ips.ts b/packages/backend/src/server/api/endpoints/admin/get-user-ips.ts deleted file mode 100644 index da76ae624e..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/get-user-ips.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { UserIps } from "@/models/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireAdmin: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const ips = await UserIps.find({ - where: { userId: ps.userId }, - order: { createdAt: "DESC" }, - take: 30, - }); - - return ips.map((x) => ({ - ip: x.ip, - createdAt: x.createdAt.toISOString(), - })); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/invite.ts b/packages/backend/src/server/api/endpoints/admin/invite.ts deleted file mode 100644 index b8bdb38b46..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/invite.ts +++ /dev/null @@ -1,50 +0,0 @@ -import rndstr from "rndstr"; -import define from "../../define.js"; -import { RegistrationTickets } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - code: { - type: "string", - optional: false, - nullable: false, - example: "2ERUA5VR", - maxLength: 8, - minLength: 8, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - const code = rndstr({ - length: 8, - chars: "2-9A-HJ-NP-Z", // [0-9A-Z] w/o [01IO] (32 patterns) - }); - - await RegistrationTickets.insert({ - id: genId(), - createdAt: new Date(), - code, - }); - - return { - code, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/admin/meta.ts b/packages/backend/src/server/api/endpoints/admin/meta.ts deleted file mode 100644 index c8c639f504..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/meta.ts +++ /dev/null @@ -1,570 +0,0 @@ -import config from "@/config/index.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { MAX_NOTE_TEXT_LENGTH, MAX_CAPTION_TEXT_LENGTH } from "@/const.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["meta"], - - requireCredential: true, - requireAdmin: true, - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - driveCapacityPerLocalUserMb: { - type: "number", - optional: false, - nullable: false, - }, - driveCapacityPerRemoteUserMb: { - type: "number", - optional: false, - nullable: false, - }, - cacheRemoteFiles: { - type: "boolean", - optional: false, - nullable: false, - }, - emailRequiredForSignup: { - type: "boolean", - optional: false, - nullable: false, - }, - enableHcaptcha: { - type: "boolean", - optional: false, - nullable: false, - }, - hcaptchaSiteKey: { - type: "string", - optional: false, - nullable: true, - }, - enableRecaptcha: { - type: "boolean", - optional: false, - nullable: false, - }, - recaptchaSiteKey: { - type: "string", - optional: false, - nullable: true, - }, - swPublickey: { - type: "string", - optional: false, - nullable: true, - }, - mascotImageUrl: { - type: "string", - optional: false, - nullable: false, - default: "/assets/ai.png", - }, - bannerUrl: { - type: "string", - optional: false, - nullable: false, - }, - errorImageUrl: { - type: "string", - optional: false, - nullable: false, - default: "https://xn--931a.moe/aiart/yubitun.png", - }, - iconUrl: { - type: "string", - optional: false, - nullable: true, - }, - maxNoteTextLength: { - type: "number", - optional: false, - nullable: false, - }, - maxCaptionTextLength: { - type: "number", - optional: false, - nullable: false, - }, - emojis: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - aliases: { - type: "array", - optional: false, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - category: { - type: "string", - optional: false, - nullable: true, - }, - host: { - type: "string", - optional: false, - nullable: true, - }, - url: { - type: "string", - optional: false, - nullable: false, - format: "url", - }, - }, - }, - }, - ads: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - properties: { - place: { - type: "string", - optional: false, - nullable: false, - }, - url: { - type: "string", - optional: false, - nullable: false, - format: "url", - }, - imageUrl: { - type: "string", - optional: false, - nullable: false, - format: "url", - }, - }, - }, - }, - enableEmail: { - type: "boolean", - optional: false, - nullable: false, - }, - enableTwitterIntegration: { - type: "boolean", - optional: false, - nullable: false, - }, - enableGithubIntegration: { - type: "boolean", - optional: false, - nullable: false, - }, - enableDiscordIntegration: { - type: "boolean", - optional: false, - nullable: false, - }, - enableServiceWorker: { - type: "boolean", - optional: false, - nullable: false, - }, - translatorAvailable: { - type: "boolean", - optional: false, - nullable: false, - }, - proxyAccountName: { - type: "string", - optional: false, - nullable: true, - }, - recommendedInstances: { - type: "array", - optional: true, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - pinnedUsers: { - type: "array", - optional: true, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - customMOTD: { - type: "array", - optional: true, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - customSplashIcons: { - type: "array", - optional: true, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - hiddenTags: { - type: "array", - optional: true, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - blockedHosts: { - type: "array", - optional: true, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - allowedHosts: { - type: "array", - optional: true, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - privateMode: { - type: "boolean", - optional: false, - nullable: false, - }, - secureMode: { - type: "boolean", - optional: false, - nullable: false, - }, - hcaptchaSecretKey: { - type: "string", - optional: true, - nullable: true, - }, - recaptchaSecretKey: { - type: "string", - optional: true, - nullable: true, - }, - sensitiveMediaDetection: { - type: "string", - optional: true, - nullable: false, - }, - sensitiveMediaDetectionSensitivity: { - type: "string", - optional: true, - nullable: false, - }, - setSensitiveFlagAutomatically: { - type: "boolean", - optional: true, - nullable: false, - }, - enableSensitiveMediaDetectionForVideos: { - type: "boolean", - optional: true, - nullable: false, - }, - proxyAccountId: { - type: "string", - optional: true, - nullable: true, - format: "id", - }, - twitterConsumerKey: { - type: "string", - optional: true, - nullable: true, - }, - twitterConsumerSecret: { - type: "string", - optional: true, - nullable: true, - }, - githubClientId: { - type: "string", - optional: true, - nullable: true, - }, - githubClientSecret: { - type: "string", - optional: true, - nullable: true, - }, - discordClientId: { - type: "string", - optional: true, - nullable: true, - }, - discordClientSecret: { - type: "string", - optional: true, - nullable: true, - }, - summaryProxy: { - type: "string", - optional: true, - nullable: true, - }, - email: { - type: "string", - optional: true, - nullable: true, - }, - smtpSecure: { - type: "boolean", - optional: true, - nullable: false, - }, - smtpHost: { - type: "string", - optional: true, - nullable: true, - }, - smtpPort: { - type: "string", - optional: true, - nullable: true, - }, - smtpUser: { - type: "string", - optional: true, - nullable: true, - }, - smtpPass: { - type: "string", - optional: true, - nullable: true, - }, - swPrivateKey: { - type: "string", - optional: true, - nullable: true, - }, - useObjectStorage: { - type: "boolean", - optional: true, - nullable: false, - }, - objectStorageBaseUrl: { - type: "string", - optional: true, - nullable: true, - }, - objectStorageBucket: { - type: "string", - optional: true, - nullable: true, - }, - objectStoragePrefix: { - type: "string", - optional: true, - nullable: true, - }, - objectStorageEndpoint: { - type: "string", - optional: true, - nullable: true, - }, - objectStorageRegion: { - type: "string", - optional: true, - nullable: true, - }, - objectStoragePort: { - type: "number", - optional: true, - nullable: true, - }, - objectStorageAccessKey: { - type: "string", - optional: true, - nullable: true, - }, - objectStorageSecretKey: { - type: "string", - optional: true, - nullable: true, - }, - objectStorageUseSSL: { - type: "boolean", - optional: true, - nullable: false, - }, - objectStorageUseProxy: { - type: "boolean", - optional: true, - nullable: false, - }, - objectStorageSetPublicRead: { - type: "boolean", - optional: true, - nullable: false, - }, - enableIpLogging: { - type: "boolean", - optional: true, - nullable: false, - }, - enableActiveEmailValidation: { - type: "boolean", - optional: true, - nullable: false, - }, - defaultReaction: { - type: "string", - optional: false, - nullable: false, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const instance = await fetchMeta(true); - - return { - maintainerName: instance.maintainerName, - maintainerEmail: instance.maintainerEmail, - version: config.version, - name: instance.name, - uri: config.url, - description: instance.description, - langs: instance.langs, - tosUrl: instance.ToSUrl, - repositoryUrl: instance.repositoryUrl, - feedbackUrl: instance.feedbackUrl, - disableRegistration: instance.disableRegistration, - disableLocalTimeline: instance.disableLocalTimeline, - disableRecommendedTimeline: instance.disableRecommendedTimeline, - disableGlobalTimeline: instance.disableGlobalTimeline, - driveCapacityPerLocalUserMb: instance.localDriveCapacityMb, - driveCapacityPerRemoteUserMb: instance.remoteDriveCapacityMb, - emailRequiredForSignup: instance.emailRequiredForSignup, - enableHcaptcha: instance.enableHcaptcha, - hcaptchaSiteKey: instance.hcaptchaSiteKey, - enableRecaptcha: instance.enableRecaptcha, - recaptchaSiteKey: instance.recaptchaSiteKey, - swPublickey: instance.swPublicKey, - themeColor: instance.themeColor, - mascotImageUrl: instance.mascotImageUrl, - bannerUrl: instance.bannerUrl, - errorImageUrl: instance.errorImageUrl, - iconUrl: instance.iconUrl, - backgroundImageUrl: instance.backgroundImageUrl, - logoImageUrl: instance.logoImageUrl, - maxNoteTextLength: MAX_NOTE_TEXT_LENGTH, // 後方互換性のため - maxCaptionTextLength: MAX_CAPTION_TEXT_LENGTH, - defaultLightTheme: instance.defaultLightTheme, - defaultDarkTheme: instance.defaultDarkTheme, - enableEmail: instance.enableEmail, - enableTwitterIntegration: instance.enableTwitterIntegration, - enableGithubIntegration: instance.enableGithubIntegration, - enableDiscordIntegration: instance.enableDiscordIntegration, - enableServiceWorker: instance.enableServiceWorker, - translatorAvailable: instance.deeplAuthKey != null, - pinnedPages: instance.pinnedPages, - pinnedClipId: instance.pinnedClipId, - cacheRemoteFiles: instance.cacheRemoteFiles, - defaultReaction: instance.defaultReaction, - recommendedInstances: instance.recommendedInstances, - pinnedUsers: instance.pinnedUsers, - customMOTD: instance.customMOTD, - customSplashIcons: instance.customSplashIcons, - hiddenTags: instance.hiddenTags, - blockedHosts: instance.blockedHosts, - allowedHosts: instance.allowedHosts, - privateMode: instance.privateMode, - secureMode: instance.secureMode, - hcaptchaSecretKey: instance.hcaptchaSecretKey, - recaptchaSecretKey: instance.recaptchaSecretKey, - sensitiveMediaDetection: instance.sensitiveMediaDetection, - sensitiveMediaDetectionSensitivity: - instance.sensitiveMediaDetectionSensitivity, - setSensitiveFlagAutomatically: instance.setSensitiveFlagAutomatically, - enableSensitiveMediaDetectionForVideos: - instance.enableSensitiveMediaDetectionForVideos, - proxyAccountId: instance.proxyAccountId, - twitterConsumerKey: instance.twitterConsumerKey, - twitterConsumerSecret: instance.twitterConsumerSecret, - githubClientId: instance.githubClientId, - githubClientSecret: instance.githubClientSecret, - discordClientId: instance.discordClientId, - discordClientSecret: instance.discordClientSecret, - summalyProxy: instance.summalyProxy, - email: instance.email, - smtpSecure: instance.smtpSecure, - smtpHost: instance.smtpHost, - smtpPort: instance.smtpPort, - smtpUser: instance.smtpUser, - smtpPass: instance.smtpPass, - swPrivateKey: instance.swPrivateKey, - useObjectStorage: instance.useObjectStorage, - objectStorageBaseUrl: instance.objectStorageBaseUrl, - objectStorageBucket: instance.objectStorageBucket, - objectStoragePrefix: instance.objectStoragePrefix, - objectStorageEndpoint: instance.objectStorageEndpoint, - objectStorageRegion: instance.objectStorageRegion, - objectStoragePort: instance.objectStoragePort, - objectStorageAccessKey: instance.objectStorageAccessKey, - objectStorageSecretKey: instance.objectStorageSecretKey, - objectStorageUseSSL: instance.objectStorageUseSSL, - objectStorageUseProxy: instance.objectStorageUseProxy, - objectStorageSetPublicRead: instance.objectStorageSetPublicRead, - objectStorageS3ForcePathStyle: instance.objectStorageS3ForcePathStyle, - deeplAuthKey: instance.deeplAuthKey, - deeplIsPro: instance.deeplIsPro, - enableIpLogging: instance.enableIpLogging, - enableActiveEmailValidation: instance.enableActiveEmailValidation, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/admin/moderators/add.ts b/packages/backend/src/server/api/endpoints/admin/moderators/add.ts deleted file mode 100644 index 478f2661b6..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/moderators/add.ts +++ /dev/null @@ -1,39 +0,0 @@ -import define from "../../../define.js"; -import { Users } from "@/models/index.js"; -import { publishInternalEvent } from "@/services/stream.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireAdmin: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps) => { - const user = await Users.findOneBy({ id: ps.userId }); - - if (user == null) { - throw new Error("user not found"); - } - - if (user.isAdmin) { - throw new Error("cannot mark as moderator if admin user"); - } - - await Users.update(user.id, { - isModerator: true, - }); - - publishInternalEvent("userChangeModeratorState", { - id: user.id, - isModerator: true, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/moderators/remove.ts b/packages/backend/src/server/api/endpoints/admin/moderators/remove.ts deleted file mode 100644 index a43cc0cbe1..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/moderators/remove.ts +++ /dev/null @@ -1,35 +0,0 @@ -import define from "../../../define.js"; -import { Users } from "@/models/index.js"; -import { publishInternalEvent } from "@/services/stream.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireAdmin: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps) => { - const user = await Users.findOneBy({ id: ps.userId }); - - if (user == null) { - throw new Error("user not found"); - } - - await Users.update(user.id, { - isModerator: false, - }); - - publishInternalEvent("userChangeModeratorState", { - id: user.id, - isModerator: false, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/promo/create.ts b/packages/backend/src/server/api/endpoints/admin/promo/create.ts deleted file mode 100644 index a6d1f35191..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/promo/create.ts +++ /dev/null @@ -1,54 +0,0 @@ -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { getNote } from "../../../common/getters.js"; -import { PromoNotes } from "@/models/index.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "ee449fbe-af2a-453b-9cae-cf2fe7c895fc", - }, - - alreadyPromoted: { - message: "The note has already promoted.", - code: "ALREADY_PROMOTED", - id: "ae427aa2-7a41-484f-a18c-2c1104051604", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - expiresAt: { type: "integer" }, - }, - required: ["noteId", "expiresAt"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - const exist = await PromoNotes.findOneBy({ noteId: note.id }); - - if (exist != null) { - throw new ApiError(meta.errors.alreadyPromoted); - } - - await PromoNotes.insert({ - noteId: note.id, - expiresAt: new Date(ps.expiresAt), - userId: note.userId, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/queue/clear.ts b/packages/backend/src/server/api/endpoints/admin/queue/clear.ts deleted file mode 100644 index 9b828bb241..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/queue/clear.ts +++ /dev/null @@ -1,22 +0,0 @@ -import define from "../../../define.js"; -import { destroy } from "@/queue/index.js"; -import { insertModerationLog } from "@/services/insert-moderation-log.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - destroy(); - - insertModerationLog(me, "clearQueue"); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/queue/deliver-delayed.ts b/packages/backend/src/server/api/endpoints/admin/queue/deliver-delayed.ts deleted file mode 100644 index 15fdfb0250..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/queue/deliver-delayed.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { deliverQueue } from "@/queue/queues.js"; -import { URL } from "node:url"; -import define from "../../../define.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "array", - optional: false, - nullable: false, - items: { - anyOf: [ - { - type: "string", - }, - { - type: "number", - }, - ], - }, - }, - example: [["example.com", 12]], - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps) => { - const jobs = await deliverQueue.getJobs(["delayed"]); - - const res = [] as [string, number][]; - - for (const job of jobs) { - const host = new URL(job.data.to).host; - if (res.find((x) => x[0] === host)) { - res.find((x) => x[0] === host)![1]++; - } else { - res.push([host, 1]); - } - } - - res.sort((a, b) => b[1] - a[1]); - - return res; -}); diff --git a/packages/backend/src/server/api/endpoints/admin/queue/inbox-delayed.ts b/packages/backend/src/server/api/endpoints/admin/queue/inbox-delayed.ts deleted file mode 100644 index 1890bd4345..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/queue/inbox-delayed.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { URL } from "node:url"; -import define from "../../../define.js"; -import { inboxQueue } from "@/queue/queues.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "array", - optional: false, - nullable: false, - items: { - anyOf: [ - { - type: "string", - }, - { - type: "number", - }, - ], - }, - }, - example: [["example.com", 12]], - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps) => { - const jobs = await inboxQueue.getJobs(["delayed"]); - - const res = [] as [string, number][]; - - for (const job of jobs) { - const host = new URL(job.data.signature.keyId).host; - if (res.find((x) => x[0] === host)) { - res.find((x) => x[0] === host)![1]++; - } else { - res.push([host, 1]); - } - } - - res.sort((a, b) => b[1] - a[1]); - - return res; -}); diff --git a/packages/backend/src/server/api/endpoints/admin/queue/stats.ts b/packages/backend/src/server/api/endpoints/admin/queue/stats.ts deleted file mode 100644 index 4a437c3d12..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/queue/stats.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { - deliverQueue, - inboxQueue, - dbQueue, - objectStorageQueue, - backgroundQueue, -} from "@/queue/queues.js"; -import define from "../../../define.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - deliver: { - optional: false, - nullable: false, - ref: "QueueCount", - }, - inbox: { - optional: false, - nullable: false, - ref: "QueueCount", - }, - db: { - optional: false, - nullable: false, - ref: "QueueCount", - }, - objectStorage: { - optional: false, - nullable: false, - ref: "QueueCount", - }, - backgroundQueue: { - optional: false, - nullable: false, - ref: "QueueCount", - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps) => { - const deliverJobCounts = await deliverQueue.getJobCounts(); - const inboxJobCounts = await inboxQueue.getJobCounts(); - const dbJobCounts = await dbQueue.getJobCounts(); - const objectStorageJobCounts = await objectStorageQueue.getJobCounts(); - const backgroundJobCounts = await backgroundQueue.getJobCounts(); - - return { - deliver: deliverJobCounts, - inbox: inboxJobCounts, - db: dbJobCounts, - objectStorage: objectStorageJobCounts, - backgroundQueue: backgroundJobCounts, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/admin/relays/add.ts b/packages/backend/src/server/api/endpoints/admin/relays/add.ts deleted file mode 100644 index bb56216a74..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/relays/add.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { URL } from "node:url"; -import define from "../../../define.js"; -import { addRelay } from "@/services/relay.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - errors: { - invalidUrl: { - message: "Invalid URL", - code: "INVALID_URL", - id: "fb8c92d3-d4e5-44e7-b3d4-800d5cef8b2c", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - inbox: { - description: "URL of the inbox, must be a https scheme URL", - type: "string", - optional: false, - nullable: false, - format: "url", - }, - status: { - type: "string", - optional: false, - nullable: false, - default: "requesting", - enum: ["requesting", "accepted", "rejected"], - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - inbox: { type: "string" }, - }, - required: ["inbox"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - try { - if (new URL(ps.inbox).protocol !== "https:") throw new Error("https only"); - } catch { - throw new ApiError(meta.errors.invalidUrl); - } - - return await addRelay(ps.inbox); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/relays/list.ts b/packages/backend/src/server/api/endpoints/admin/relays/list.ts deleted file mode 100644 index 4c294ba9b2..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/relays/list.ts +++ /dev/null @@ -1,51 +0,0 @@ -import define from "../../../define.js"; -import { listRelay } from "@/services/relay.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - inbox: { - type: "string", - optional: false, - nullable: false, - format: "url", - }, - status: { - type: "string", - optional: false, - nullable: false, - default: "requesting", - enum: ["requesting", "accepted", "rejected"], - }, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - return await listRelay(); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/relays/remove.ts b/packages/backend/src/server/api/endpoints/admin/relays/remove.ts deleted file mode 100644 index 1b3d90628b..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/relays/remove.ts +++ /dev/null @@ -1,21 +0,0 @@ -import define from "../../../define.js"; -import { removeRelay } from "@/services/relay.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - inbox: { type: "string" }, - }, - required: ["inbox"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - return await removeRelay(ps.inbox); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/reset-password.ts b/packages/backend/src/server/api/endpoints/admin/reset-password.ts deleted file mode 100644 index cbe6735ce5..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/reset-password.ts +++ /dev/null @@ -1,66 +0,0 @@ -import define from "../../define.js"; -// import bcrypt from "bcryptjs"; -import rndstr from "rndstr"; -import { Users, UserProfiles } from "@/models/index.js"; -import { hashPassword } from "@/misc/password.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - password: { - type: "string", - optional: false, - nullable: false, - minLength: 8, - maxLength: 8, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps) => { - const user = await Users.findOneBy({ id: ps.userId }); - - if (user == null) { - throw new Error("user not found"); - } - - if (user.isAdmin) { - throw new Error("cannot reset password of admin"); - } - - const passwd = rndstr("a-zA-Z0-9", 8); - - // Generate hash of password - // const hash = bcrypt.hashSync(passwd); - const hash = await hashPassword(passwd); - - await UserProfiles.update( - { - userId: user.id, - }, - { - password: hash, - }, - ); - - return { - password: passwd, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/admin/resolve-abuse-user-report.ts b/packages/backend/src/server/api/endpoints/admin/resolve-abuse-user-report.ts deleted file mode 100644 index c876a21984..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/resolve-abuse-user-report.ts +++ /dev/null @@ -1,47 +0,0 @@ -import define from "../../define.js"; -import { AbuseUserReports, Users } from "@/models/index.js"; -import { getInstanceActor } from "@/services/instance-actor.js"; -import { deliver } from "@/queue/index.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import { renderFlag } from "@/remote/activitypub/renderer/flag.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - reportId: { type: "string", format: "misskey:id" }, - forward: { type: "boolean", default: false }, - }, - required: ["reportId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const report = await AbuseUserReports.findOneByOrFail({ id: ps.reportId }); - - if (report == null) { - throw new Error("report not found"); - } - - if (ps.forward && report.targetUserHost != null) { - const actor = await getInstanceActor(); - const targetUser = await Users.findOneByOrFail({ id: report.targetUserId }); - - deliver( - actor, - renderActivity(renderFlag(actor, [targetUser.uri!], report.comment)), - targetUser.inbox, - ); - } - - await AbuseUserReports.update(report.id, { - resolved: true, - assigneeId: me.id, - forwarded: ps.forward && report.targetUserHost != null, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/search/index-all.ts b/packages/backend/src/server/api/endpoints/admin/search/index-all.ts deleted file mode 100644 index 135b48eccd..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/search/index-all.ts +++ /dev/null @@ -1,28 +0,0 @@ -import define from "../../../define.js"; -import { createIndexAllNotesJob } from "@/queue/index.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - cursor: { - type: "string", - format: "misskey:id", - nullable: true, - default: null, - }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, _me) => { - createIndexAllNotesJob({ - cursor: ps.cursor ?? undefined, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/send-email.ts b/packages/backend/src/server/api/endpoints/admin/send-email.ts deleted file mode 100644 index 1676f68907..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/send-email.ts +++ /dev/null @@ -1,23 +0,0 @@ -import define from "../../define.js"; -import { sendEmail } from "@/services/send-email.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - to: { type: "string" }, - subject: { type: "string" }, - text: { type: "string" }, - }, - required: ["to", "subject", "text"], -} as const; - -export default define(meta, paramDef, async (ps) => { - await sendEmail(ps.to, ps.subject, ps.text, ps.text); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/server-info.ts b/packages/backend/src/server/api/endpoints/admin/server-info.ts deleted file mode 100644 index 8998032cc9..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/server-info.ts +++ /dev/null @@ -1,143 +0,0 @@ -import * as os from "node:os"; -import si from "systeminformation"; -import define from "../../define.js"; -import { redisClient } from "../../../../db/redis.js"; -import { db } from "@/db/postgre.js"; - -export const meta = { - requireCredential: true, - requireModerator: true, - - tags: ["admin", "meta"], - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - machine: { - type: "string", - optional: false, - nullable: false, - }, - os: { - type: "string", - optional: false, - nullable: false, - example: "linux", - }, - node: { - type: "string", - optional: false, - nullable: false, - }, - psql: { - type: "string", - optional: false, - nullable: false, - }, - cpu: { - type: "object", - optional: false, - nullable: false, - properties: { - model: { - type: "string", - optional: false, - nullable: false, - }, - cores: { - type: "number", - optional: false, - nullable: false, - }, - }, - }, - mem: { - type: "object", - optional: false, - nullable: false, - properties: { - total: { - type: "number", - optional: false, - nullable: false, - format: "bytes", - }, - }, - }, - fs: { - type: "object", - optional: false, - nullable: false, - properties: { - total: { - type: "number", - optional: false, - nullable: false, - format: "bytes", - }, - used: { - type: "number", - optional: false, - nullable: false, - format: "bytes", - }, - }, - }, - net: { - type: "object", - optional: false, - nullable: false, - properties: { - interface: { - type: "string", - optional: false, - nullable: false, - example: "eth0", - }, - }, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - const memStats = await si.mem(); - const fsStats = await si.fsSize(); - const netInterface = await si.networkInterfaceDefault(); - - const redisServerInfo = await redisClient.info("Server"); - const m = redisServerInfo.match(new RegExp("^redis_version:(.*)", "m")); - const redis_version = m?.[1]; - - return { - machine: os.hostname(), - os: os.platform(), - node: process.version, - psql: await db - .query("SHOW server_version") - .then((x) => x[0].server_version), - redis: redis_version, - cpu: { - model: os.cpus()[0].model, - cores: os.cpus().length, - }, - mem: { - total: memStats.total, - }, - fs: { - total: fsStats[0].size, - used: fsStats[0].used, - }, - net: { - interface: netInterface, - }, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/admin/show-moderation-logs.ts b/packages/backend/src/server/api/endpoints/admin/show-moderation-logs.ts deleted file mode 100644 index df7e8979ca..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/show-moderation-logs.ts +++ /dev/null @@ -1,79 +0,0 @@ -import define from "../../define.js"; -import { ModerationLogs } from "@/models/index.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - type: { - type: "string", - optional: false, - nullable: false, - }, - info: { - type: "object", - optional: false, - nullable: false, - }, - userId: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - user: { - type: "object", - optional: false, - nullable: false, - ref: "UserDetailed", - }, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps) => { - const query = makePaginationQuery( - ModerationLogs.createQueryBuilder("report"), - ps.sinceId, - ps.untilId, - ); - - const reports = await query.take(ps.limit).getMany(); - - return await ModerationLogs.packMany(reports); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/show-user.ts b/packages/backend/src/server/api/endpoints/admin/show-user.ts deleted file mode 100644 index e91f07f838..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/show-user.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { Signins, UserProfiles, Users } from "@/models/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - res: { - type: "object", - nullable: false, - optional: false, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const [user, profile] = await Promise.all([ - Users.findOneBy({ id: ps.userId }), - UserProfiles.findOneBy({ userId: ps.userId }), - ]); - - if (user == null || profile == null) { - throw new Error("user not found"); - } - - const _me = await Users.findOneByOrFail({ id: me.id }); - if (_me.isModerator && !_me.isAdmin && user.isAdmin) { - throw new Error("cannot show info of admin"); - } - - if (!_me.isAdmin) { - return { - isModerator: user.isModerator, - isSilenced: user.isSilenced, - isSuspended: user.isSuspended, - }; - } - - const maskedKeys = ["accessToken", "accessTokenSecret", "refreshToken"]; - Object.keys(profile.integrations).forEach((integration) => { - maskedKeys.forEach( - (key) => (profile.integrations[integration][key] = "<MASKED>"), - ); - }); - - const signins = await Signins.findBy({ userId: user.id }); - - return { - email: profile.email, - emailVerified: profile.emailVerified, - autoAcceptFollowed: profile.autoAcceptFollowed, - noCrawle: profile.noCrawle, - alwaysMarkNsfw: profile.alwaysMarkNsfw, - autoSensitive: profile.autoSensitive, - carefulBot: profile.carefulBot, - injectFeaturedNote: profile.injectFeaturedNote, - receiveAnnouncementEmail: profile.receiveAnnouncementEmail, - integrations: profile.integrations, - mutedWords: profile.mutedWords, - mutedInstances: profile.mutedInstances, - mutingNotificationTypes: profile.mutingNotificationTypes, - isModerator: user.isModerator, - isSilenced: user.isSilenced, - isSuspended: user.isSuspended, - lastActiveDate: user.lastActiveDate, - moderationNote: profile.moderationNote, - signins, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/admin/show-users.ts b/packages/backend/src/server/api/endpoints/admin/show-users.ts deleted file mode 100644 index 868df9dc9b..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/show-users.ts +++ /dev/null @@ -1,149 +0,0 @@ -import { Users } from "@/models/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, - - res: { - type: "array", - nullable: false, - optional: false, - items: { - type: "object", - nullable: false, - optional: false, - ref: "UserDetailed", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - offset: { type: "integer", default: 0 }, - sort: { - type: "string", - enum: [ - "+follower", - "-follower", - "+createdAt", - "-createdAt", - "+updatedAt", - "-updatedAt", - ], - }, - state: { - type: "string", - enum: [ - "all", - "alive", - "available", - "admin", - "moderator", - "adminOrModerator", - "silenced", - "suspended", - ], - default: "all", - }, - origin: { - type: "string", - enum: ["combined", "local", "remote"], - default: "combined", - }, - username: { type: "string", nullable: true, default: null }, - hostname: { - type: "string", - nullable: true, - default: null, - description: "The local host is represented with `null`.", - }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = Users.createQueryBuilder("user"); - - switch (ps.state) { - case "available": - query.where("user.isSuspended = FALSE"); - break; - case "admin": - query.where("user.isAdmin = TRUE"); - break; - case "moderator": - query.where("user.isModerator = TRUE"); - break; - case "adminOrModerator": - query.where("user.isAdmin = TRUE OR user.isModerator = TRUE"); - break; - case "alive": - query.where("user.updatedAt > :date", { - date: new Date(Date.now() - 1000 * 60 * 60 * 24 * 5), - }); - break; - case "silenced": - query.where("user.isSilenced = TRUE"); - break; - case "suspended": - query.where("user.isSuspended = TRUE"); - break; - } - - switch (ps.origin) { - case "local": - query.andWhere("user.host IS NULL"); - break; - case "remote": - query.andWhere("user.host IS NOT NULL"); - break; - } - - if (ps.username) { - query.andWhere("user.usernameLower like :username", { - username: `${ps.username.toLowerCase()}%`, - }); - } - - if (ps.hostname) { - query.andWhere("user.host = :hostname", { - hostname: ps.hostname.toLowerCase(), - }); - } - - switch (ps.sort) { - case "+follower": - query.orderBy("user.followersCount", "DESC"); - break; - case "-follower": - query.orderBy("user.followersCount", "ASC"); - break; - case "+createdAt": - query.orderBy("user.createdAt", "DESC"); - break; - case "-createdAt": - query.orderBy("user.createdAt", "ASC"); - break; - case "+updatedAt": - query.orderBy("user.updatedAt", "DESC", "NULLS LAST"); - break; - case "-updatedAt": - query.orderBy("user.updatedAt", "ASC", "NULLS FIRST"); - break; - default: - query.orderBy("user.id", "ASC"); - break; - } - - query.take(ps.limit); - query.skip(ps.offset); - - const users = await query.getMany(); - - return await Users.packMany(users, me, { detail: true }); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/silence-user.ts b/packages/backend/src/server/api/endpoints/admin/silence-user.ts deleted file mode 100644 index a61823297b..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/silence-user.ts +++ /dev/null @@ -1,44 +0,0 @@ -import define from "../../define.js"; -import { Users } from "@/models/index.js"; -import { insertModerationLog } from "@/services/insert-moderation-log.js"; -import { publishInternalEvent } from "@/services/stream.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const user = await Users.findOneBy({ id: ps.userId }); - - if (user == null) { - throw new Error("user not found"); - } - - if (user.isAdmin) { - throw new Error("cannot silence admin"); - } - - await Users.update(user.id, { - isSilenced: true, - }); - - publishInternalEvent("userChangeSilencedState", { - id: user.id, - isSilenced: true, - }); - - insertModerationLog(me, "silence", { - targetId: user.id, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/suspend-user.ts b/packages/backend/src/server/api/endpoints/admin/suspend-user.ts deleted file mode 100644 index 984bc0789e..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/suspend-user.ts +++ /dev/null @@ -1,87 +0,0 @@ -import define from "../../define.js"; -import deleteFollowing from "@/services/following/delete.js"; -import { Users, Followings, Notifications } from "@/models/index.js"; -import type { User } from "@/models/entities/user.js"; -import { insertModerationLog } from "@/services/insert-moderation-log.js"; -import { doPostSuspend } from "@/services/suspend-user.js"; -import { publishUserEvent } from "@/services/stream.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const user = await Users.findOneBy({ id: ps.userId }); - - if (user == null) { - throw new Error("user not found"); - } - - if (user.isAdmin) { - throw new Error("cannot suspend admin"); - } - - if (user.isModerator) { - throw new Error("cannot suspend moderator"); - } - - await Users.update(user.id, { - isSuspended: true, - }); - - insertModerationLog(me, "suspend", { - targetId: user.id, - }); - - // Terminate streaming - if (Users.isLocalUser(user)) { - publishUserEvent(user.id, "terminate", {}); - } - - (async () => { - await doPostSuspend(user).catch((e) => {}); - await unFollowAll(user).catch((e) => {}); - await readAllNotify(user).catch((e) => {}); - })(); -}); - -async function unFollowAll(follower: User) { - const followings = await Followings.findBy({ - followerId: follower.id, - }); - - for (const following of followings) { - const followee = await Users.findOneBy({ - id: following.followeeId, - }); - - if (followee == null) { - throw new Error(`Cant find followee ${following.followeeId}`); - } - - await deleteFollowing(follower, followee, true); - } -} - -async function readAllNotify(notifier: User) { - await Notifications.update( - { - notifierId: notifier.id, - isRead: false, - }, - { - isRead: true, - }, - ); -} diff --git a/packages/backend/src/server/api/endpoints/admin/unsilence-user.ts b/packages/backend/src/server/api/endpoints/admin/unsilence-user.ts deleted file mode 100644 index 6a01b8e8d3..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/unsilence-user.ts +++ /dev/null @@ -1,40 +0,0 @@ -import define from "../../define.js"; -import { Users } from "@/models/index.js"; -import { insertModerationLog } from "@/services/insert-moderation-log.js"; -import { publishInternalEvent } from "@/services/stream.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const user = await Users.findOneBy({ id: ps.userId }); - - if (user == null) { - throw new Error("user not found"); - } - - await Users.update(user.id, { - isSilenced: false, - }); - - publishInternalEvent("userChangeSilencedState", { - id: user.id, - isSilenced: false, - }); - - insertModerationLog(me, "unsilence", { - targetId: user.id, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/unsuspend-user.ts b/packages/backend/src/server/api/endpoints/admin/unsuspend-user.ts deleted file mode 100644 index e51d5851c2..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/unsuspend-user.ts +++ /dev/null @@ -1,37 +0,0 @@ -import define from "../../define.js"; -import { Users } from "@/models/index.js"; -import { insertModerationLog } from "@/services/insert-moderation-log.js"; -import { doPostUnsuspend } from "@/services/unsuspend-user.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const user = await Users.findOneBy({ id: ps.userId }); - - if (user == null) { - throw new Error("user not found"); - } - - await Users.update(user.id, { - isSuspended: false, - }); - - insertModerationLog(me, "unsuspend", { - targetId: user.id, - }); - - doPostUnsuspend(user); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/update-meta.ts b/packages/backend/src/server/api/endpoints/admin/update-meta.ts deleted file mode 100644 index f7e79b64b5..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/update-meta.ts +++ /dev/null @@ -1,543 +0,0 @@ -import { Meta } from "@/models/entities/meta.js"; -import { insertModerationLog } from "@/services/insert-moderation-log.js"; -import { DB_MAX_NOTE_TEXT_LENGTH } from "@/misc/hard-limits.js"; -import { db } from "@/db/postgre.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireAdmin: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - disableRegistration: { type: "boolean", nullable: true }, - disableLocalTimeline: { type: "boolean", nullable: true }, - disableRecommendedTimeline: { type: "boolean", nullable: true }, - disableGlobalTimeline: { type: "boolean", nullable: true }, - defaultReaction: { type: "string", nullable: true }, - recommendedInstances: { - type: "array", - nullable: true, - items: { - type: "string", - }, - }, - pinnedUsers: { - type: "array", - nullable: true, - items: { - type: "string", - }, - }, - customMOTD: { - type: "array", - nullable: true, - items: { - type: "string", - }, - }, - customSplashIcons: { - type: "array", - nullable: true, - items: { - type: "string", - }, - }, - hiddenTags: { - type: "array", - nullable: true, - items: { - type: "string", - }, - }, - blockedHosts: { - type: "array", - nullable: true, - items: { - type: "string", - }, - }, - allowedHosts: { - type: "array", - nullable: true, - items: { - type: "string", - }, - }, - secureMode: { type: "boolean", nullable: true }, - privateMode: { type: "boolean", nullable: true }, - themeColor: { - type: "string", - nullable: true, - pattern: "^#[0-9a-fA-F]{6}$", - }, - mascotImageUrl: { type: "string", nullable: true }, - bannerUrl: { type: "string", nullable: true }, - logoImageUrl: { type: "string", nullable: true }, - errorImageUrl: { type: "string", nullable: true }, - iconUrl: { type: "string", nullable: true }, - backgroundImageUrl: { type: "string", nullable: true }, - name: { type: "string", nullable: true }, - description: { type: "string", nullable: true }, - defaultLightTheme: { type: "string", nullable: true }, - defaultDarkTheme: { type: "string", nullable: true }, - localDriveCapacityMb: { type: "integer" }, - remoteDriveCapacityMb: { type: "integer" }, - cacheRemoteFiles: { type: "boolean" }, - emailRequiredForSignup: { type: "boolean" }, - enableHcaptcha: { type: "boolean" }, - hcaptchaSiteKey: { type: "string", nullable: true }, - hcaptchaSecretKey: { type: "string", nullable: true }, - enableRecaptcha: { type: "boolean" }, - recaptchaSiteKey: { type: "string", nullable: true }, - recaptchaSecretKey: { type: "string", nullable: true }, - sensitiveMediaDetection: { - type: "string", - enum: ["none", "all", "local", "remote"], - }, - sensitiveMediaDetectionSensitivity: { - type: "string", - enum: ["medium", "low", "high", "veryLow", "veryHigh"], - }, - setSensitiveFlagAutomatically: { type: "boolean" }, - enableSensitiveMediaDetectionForVideos: { type: "boolean" }, - proxyAccountId: { type: "string", format: "misskey:id", nullable: true }, - maintainerName: { type: "string", nullable: true }, - maintainerEmail: { type: "string", nullable: true }, - pinnedPages: { - type: "array", - items: { - type: "string", - }, - }, - pinnedClipId: { type: "string", format: "misskey:id", nullable: true }, - langs: { - type: "array", - items: { - type: "string", - }, - }, - summalyProxy: { type: "string", nullable: true }, - deeplAuthKey: { type: "string", nullable: true }, - deeplIsPro: { type: "boolean" }, - enableTwitterIntegration: { type: "boolean" }, - twitterConsumerKey: { type: "string", nullable: true }, - twitterConsumerSecret: { type: "string", nullable: true }, - enableGithubIntegration: { type: "boolean" }, - githubClientId: { type: "string", nullable: true }, - githubClientSecret: { type: "string", nullable: true }, - enableDiscordIntegration: { type: "boolean" }, - discordClientId: { type: "string", nullable: true }, - discordClientSecret: { type: "string", nullable: true }, - enableEmail: { type: "boolean" }, - email: { type: "string", nullable: true }, - smtpSecure: { type: "boolean" }, - smtpHost: { type: "string", nullable: true }, - smtpPort: { type: "integer", nullable: true }, - smtpUser: { type: "string", nullable: true }, - smtpPass: { type: "string", nullable: true }, - enableServiceWorker: { type: "boolean" }, - swPublicKey: { type: "string", nullable: true }, - swPrivateKey: { type: "string", nullable: true }, - tosUrl: { type: "string", nullable: true }, - repositoryUrl: { type: "string" }, - feedbackUrl: { type: "string" }, - useObjectStorage: { type: "boolean" }, - objectStorageBaseUrl: { type: "string", nullable: true }, - objectStorageBucket: { type: "string", nullable: true }, - objectStoragePrefix: { type: "string", nullable: true }, - objectStorageEndpoint: { type: "string", nullable: true }, - objectStorageRegion: { type: "string", nullable: true }, - objectStoragePort: { type: "integer", nullable: true }, - objectStorageAccessKey: { type: "string", nullable: true }, - objectStorageSecretKey: { type: "string", nullable: true }, - objectStorageUseSSL: { type: "boolean" }, - objectStorageUseProxy: { type: "boolean" }, - objectStorageSetPublicRead: { type: "boolean" }, - objectStorageS3ForcePathStyle: { type: "boolean" }, - enableIpLogging: { type: "boolean" }, - enableActiveEmailValidation: { type: "boolean" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const set = {} as Partial<Meta>; - - if (typeof ps.disableRegistration === "boolean") { - set.disableRegistration = ps.disableRegistration; - } - - if (typeof ps.disableLocalTimeline === "boolean") { - set.disableLocalTimeline = ps.disableLocalTimeline; - } - - if (typeof ps.disableRecommendedTimeline === "boolean") { - set.disableRecommendedTimeline = ps.disableRecommendedTimeline; - } - - if (typeof ps.disableGlobalTimeline === "boolean") { - set.disableGlobalTimeline = ps.disableGlobalTimeline; - } - - if (typeof ps.defaultReaction === "string") { - set.defaultReaction = ps.defaultReaction; - } - - if (Array.isArray(ps.pinnedUsers)) { - set.pinnedUsers = ps.pinnedUsers.filter(Boolean); - } - - if (Array.isArray(ps.customMOTD)) { - set.customMOTD = ps.customMOTD.filter(Boolean); - } - - if (Array.isArray(ps.customSplashIcons)) { - set.customSplashIcons = ps.customSplashIcons.filter(Boolean); - } - - if (Array.isArray(ps.recommendedInstances)) { - set.recommendedInstances = ps.recommendedInstances.filter(Boolean); - } - - if (Array.isArray(ps.hiddenTags)) { - set.hiddenTags = ps.hiddenTags.filter(Boolean); - } - - if (Array.isArray(ps.blockedHosts)) { - let lastValue = ""; - set.blockedHosts = ps.blockedHosts.sort().filter((h) => { - const lv = lastValue; - lastValue = h; - return h !== "" && h !== lv; - }); - } - - if (ps.themeColor !== undefined) { - set.themeColor = ps.themeColor; - } - - if (Array.isArray(ps.allowedHosts)) { - set.allowedHosts = ps.allowedHosts.filter(Boolean); - } - - if (typeof ps.privateMode === "boolean") { - set.privateMode = ps.privateMode; - } - - if (typeof ps.secureMode === "boolean") { - set.secureMode = ps.secureMode; - } - - if (ps.mascotImageUrl !== undefined) { - set.mascotImageUrl = ps.mascotImageUrl; - } - - if (ps.bannerUrl !== undefined) { - set.bannerUrl = ps.bannerUrl; - } - - if (ps.logoImageUrl !== undefined) { - set.logoImageUrl = ps.logoImageUrl; - } - - if (ps.iconUrl !== undefined) { - set.iconUrl = ps.iconUrl; - } - - if (ps.backgroundImageUrl !== undefined) { - set.backgroundImageUrl = ps.backgroundImageUrl; - } - - if (ps.logoImageUrl !== undefined) { - set.logoImageUrl = ps.logoImageUrl; - } - - if (ps.name !== undefined) { - set.name = ps.name; - } - - if (ps.description !== undefined) { - set.description = ps.description; - } - - if (ps.defaultLightTheme !== undefined) { - set.defaultLightTheme = ps.defaultLightTheme; - } - - if (ps.defaultDarkTheme !== undefined) { - set.defaultDarkTheme = ps.defaultDarkTheme; - } - - if (ps.localDriveCapacityMb !== undefined) { - set.localDriveCapacityMb = ps.localDriveCapacityMb; - } - - if (ps.remoteDriveCapacityMb !== undefined) { - set.remoteDriveCapacityMb = ps.remoteDriveCapacityMb; - } - - if (ps.cacheRemoteFiles !== undefined) { - set.cacheRemoteFiles = ps.cacheRemoteFiles; - } - - if (ps.emailRequiredForSignup !== undefined) { - set.emailRequiredForSignup = ps.emailRequiredForSignup; - } - - if (ps.enableHcaptcha !== undefined) { - set.enableHcaptcha = ps.enableHcaptcha; - } - - if (ps.hcaptchaSiteKey !== undefined) { - set.hcaptchaSiteKey = ps.hcaptchaSiteKey; - } - - if (ps.hcaptchaSecretKey !== undefined) { - set.hcaptchaSecretKey = ps.hcaptchaSecretKey; - } - - if (ps.enableRecaptcha !== undefined) { - set.enableRecaptcha = ps.enableRecaptcha; - } - - if (ps.recaptchaSiteKey !== undefined) { - set.recaptchaSiteKey = ps.recaptchaSiteKey; - } - - if (ps.recaptchaSecretKey !== undefined) { - set.recaptchaSecretKey = ps.recaptchaSecretKey; - } - - if (ps.sensitiveMediaDetection !== undefined) { - set.sensitiveMediaDetection = ps.sensitiveMediaDetection; - } - - if (ps.sensitiveMediaDetectionSensitivity !== undefined) { - set.sensitiveMediaDetectionSensitivity = - ps.sensitiveMediaDetectionSensitivity; - } - - if (ps.setSensitiveFlagAutomatically !== undefined) { - set.setSensitiveFlagAutomatically = ps.setSensitiveFlagAutomatically; - } - - if (ps.enableSensitiveMediaDetectionForVideos !== undefined) { - set.enableSensitiveMediaDetectionForVideos = - ps.enableSensitiveMediaDetectionForVideos; - } - - if (ps.proxyAccountId !== undefined) { - set.proxyAccountId = ps.proxyAccountId; - } - - if (ps.maintainerName !== undefined) { - set.maintainerName = ps.maintainerName; - } - - if (ps.maintainerEmail !== undefined) { - set.maintainerEmail = ps.maintainerEmail; - } - - if (Array.isArray(ps.langs)) { - set.langs = ps.langs.filter(Boolean); - } - - if (Array.isArray(ps.pinnedPages)) { - set.pinnedPages = ps.pinnedPages.filter(Boolean); - } - - if (ps.pinnedClipId !== undefined) { - set.pinnedClipId = ps.pinnedClipId; - } - - if (ps.summalyProxy !== undefined) { - set.summalyProxy = ps.summalyProxy; - } - - if (ps.enableTwitterIntegration !== undefined) { - set.enableTwitterIntegration = ps.enableTwitterIntegration; - } - - if (ps.twitterConsumerKey !== undefined) { - set.twitterConsumerKey = ps.twitterConsumerKey; - } - - if (ps.twitterConsumerSecret !== undefined) { - set.twitterConsumerSecret = ps.twitterConsumerSecret; - } - - if (ps.enableGithubIntegration !== undefined) { - set.enableGithubIntegration = ps.enableGithubIntegration; - } - - if (ps.githubClientId !== undefined) { - set.githubClientId = ps.githubClientId; - } - - if (ps.githubClientSecret !== undefined) { - set.githubClientSecret = ps.githubClientSecret; - } - - if (ps.enableDiscordIntegration !== undefined) { - set.enableDiscordIntegration = ps.enableDiscordIntegration; - } - - if (ps.discordClientId !== undefined) { - set.discordClientId = ps.discordClientId; - } - - if (ps.discordClientSecret !== undefined) { - set.discordClientSecret = ps.discordClientSecret; - } - - if (ps.enableEmail !== undefined) { - set.enableEmail = ps.enableEmail; - } - - if (ps.email !== undefined) { - set.email = ps.email; - } - - if (ps.smtpSecure !== undefined) { - set.smtpSecure = ps.smtpSecure; - } - - if (ps.smtpHost !== undefined) { - set.smtpHost = ps.smtpHost; - } - - if (ps.smtpPort !== undefined) { - set.smtpPort = ps.smtpPort; - } - - if (ps.smtpUser !== undefined) { - set.smtpUser = ps.smtpUser; - } - - if (ps.smtpPass !== undefined) { - set.smtpPass = ps.smtpPass; - } - - if (ps.errorImageUrl !== undefined) { - set.errorImageUrl = ps.errorImageUrl; - } - - if (ps.enableServiceWorker !== undefined) { - set.enableServiceWorker = ps.enableServiceWorker; - } - - if (ps.swPublicKey !== undefined) { - set.swPublicKey = ps.swPublicKey; - } - - if (ps.swPrivateKey !== undefined) { - set.swPrivateKey = ps.swPrivateKey; - } - - if (ps.tosUrl !== undefined) { - set.ToSUrl = ps.tosUrl; - } - - if (ps.repositoryUrl !== undefined) { - set.repositoryUrl = ps.repositoryUrl; - } - - if (ps.feedbackUrl !== undefined) { - set.feedbackUrl = ps.feedbackUrl; - } - - if (ps.useObjectStorage !== undefined) { - set.useObjectStorage = ps.useObjectStorage; - } - - if (ps.objectStorageBaseUrl !== undefined) { - set.objectStorageBaseUrl = ps.objectStorageBaseUrl; - } - - if (ps.objectStorageBucket !== undefined) { - set.objectStorageBucket = ps.objectStorageBucket; - } - - if (ps.objectStoragePrefix !== undefined) { - set.objectStoragePrefix = ps.objectStoragePrefix; - } - - if (ps.objectStorageEndpoint !== undefined) { - set.objectStorageEndpoint = ps.objectStorageEndpoint; - } - - if (ps.objectStorageRegion !== undefined) { - set.objectStorageRegion = ps.objectStorageRegion; - } - - if (ps.objectStoragePort !== undefined) { - set.objectStoragePort = ps.objectStoragePort; - } - - if (ps.objectStorageAccessKey !== undefined) { - set.objectStorageAccessKey = ps.objectStorageAccessKey; - } - - if (ps.objectStorageSecretKey !== undefined) { - set.objectStorageSecretKey = ps.objectStorageSecretKey; - } - - if (ps.objectStorageUseSSL !== undefined) { - set.objectStorageUseSSL = ps.objectStorageUseSSL; - } - - if (ps.objectStorageUseProxy !== undefined) { - set.objectStorageUseProxy = ps.objectStorageUseProxy; - } - - if (ps.objectStorageSetPublicRead !== undefined) { - set.objectStorageSetPublicRead = ps.objectStorageSetPublicRead; - } - - if (ps.objectStorageS3ForcePathStyle !== undefined) { - set.objectStorageS3ForcePathStyle = ps.objectStorageS3ForcePathStyle; - } - - if (ps.deeplAuthKey !== undefined) { - if (ps.deeplAuthKey === "") { - set.deeplAuthKey = null; - } else { - set.deeplAuthKey = ps.deeplAuthKey; - } - } - - if (ps.deeplIsPro !== undefined) { - set.deeplIsPro = ps.deeplIsPro; - } - - if (ps.enableIpLogging !== undefined) { - set.enableIpLogging = ps.enableIpLogging; - } - - if (ps.enableActiveEmailValidation !== undefined) { - set.enableActiveEmailValidation = ps.enableActiveEmailValidation; - } - - await db.transaction(async (transactionalEntityManager) => { - const metas = await transactionalEntityManager.find(Meta, { - order: { - id: "DESC", - }, - }); - - const meta = metas[0]; - - if (meta) { - await transactionalEntityManager.update(Meta, meta.id, set); - } else { - await transactionalEntityManager.save(Meta, set); - } - }); - - insertModerationLog(me, "updateMeta"); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/update-user-note.ts b/packages/backend/src/server/api/endpoints/admin/update-user-note.ts deleted file mode 100644 index 04870d1c1c..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/update-user-note.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { UserProfiles, Users } from "@/models/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - text: { type: "string" }, - }, - required: ["userId", "text"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const user = await Users.findOneBy({ id: ps.userId }); - - if (user == null) { - throw new Error("user not found"); - } - - await UserProfiles.update( - { userId: user.id }, - { - moderationNote: ps.text, - }, - ); -}); diff --git a/packages/backend/src/server/api/endpoints/admin/vacuum.ts b/packages/backend/src/server/api/endpoints/admin/vacuum.ts deleted file mode 100644 index 559b310e46..0000000000 --- a/packages/backend/src/server/api/endpoints/admin/vacuum.ts +++ /dev/null @@ -1,35 +0,0 @@ -import define from "../../define.js"; -import { insertModerationLog } from "@/services/insert-moderation-log.js"; -import { db } from "@/db/postgre.js"; - -export const meta = { - tags: ["admin"], - - requireCredential: true, - requireModerator: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - full: { type: "boolean" }, - analyze: { type: "boolean" }, - }, - required: ["full", "analyze"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const params: string[] = []; - - if (ps.full) { - params.push("FULL"); - } - - if (ps.analyze) { - params.push("ANALYZE"); - } - - db.query(`VACUUM ${params.join(" ")}`); - - insertModerationLog(me, "vacuum", ps); -}); diff --git a/packages/backend/src/server/api/endpoints/announcements.ts b/packages/backend/src/server/api/endpoints/announcements.ts deleted file mode 100644 index 00634cc421..0000000000 --- a/packages/backend/src/server/api/endpoints/announcements.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { Announcements, AnnouncementReads } from "@/models/index.js"; -import define from "../define.js"; -import { makePaginationQuery } from "../common/make-pagination-query.js"; - -export const meta = { - tags: ["meta"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - example: "xxxxxxxxxx", - }, - createdAt: { - type: "string", - optional: false, - nullable: false, - format: "date-time", - }, - updatedAt: { - type: "string", - optional: false, - nullable: true, - format: "date-time", - }, - text: { - type: "string", - optional: false, - nullable: false, - }, - title: { - type: "string", - optional: false, - nullable: false, - }, - imageUrl: { - type: "string", - optional: false, - nullable: true, - }, - isRead: { - type: "boolean", - optional: true, - nullable: false, - }, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - withUnreads: { type: "boolean", default: false }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = makePaginationQuery( - Announcements.createQueryBuilder("announcement"), - ps.sinceId, - ps.untilId, - ); - - const announcements = await query.take(ps.limit).getMany(); - - if (user) { - const reads = ( - await AnnouncementReads.findBy({ - userId: user.id, - }) - ).map((x) => x.announcementId); - - for (const announcement of announcements) { - (announcement as any).isRead = reads.includes(announcement.id); - } - } - - return ( - ps.withUnreads ? announcements.filter((a: any) => !a.isRead) : announcements - ).map((a) => ({ - ...a, - createdAt: a.createdAt.toISOString(), - updatedAt: a.updatedAt?.toISOString() ?? null, - })); -}); diff --git a/packages/backend/src/server/api/endpoints/antennas/create.ts b/packages/backend/src/server/api/endpoints/antennas/create.ts deleted file mode 100644 index c1ba7bcdfd..0000000000 --- a/packages/backend/src/server/api/endpoints/antennas/create.ts +++ /dev/null @@ -1,141 +0,0 @@ -import define from "../../define.js"; -import { genId } from "@/misc/gen-id.js"; -import { Antennas, UserLists, UserGroupJoinings } from "@/models/index.js"; -import { ApiError } from "../../error.js"; -import { publishInternalEvent } from "@/services/stream.js"; - -export const meta = { - tags: ["antennas"], - - requireCredential: true, - - kind: "write:account", - - errors: { - noSuchUserList: { - message: "No such user list.", - code: "NO_SUCH_USER_LIST", - id: "95063e93-a283-4b8b-9aa5-bcdb8df69a7f", - }, - - noSuchUserGroup: { - message: "No such user group.", - code: "NO_SUCH_USER_GROUP", - id: "aa3c0b9a-8cae-47c0-92ac-202ce5906682", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "Antenna", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - name: { type: "string", minLength: 1, maxLength: 100 }, - src: { - type: "string", - enum: ["home", "all", "users", "list", "group", "instances"], - }, - userListId: { type: "string", format: "misskey:id", nullable: true }, - userGroupId: { type: "string", format: "misskey:id", nullable: true }, - keywords: { - type: "array", - items: { - type: "array", - items: { - type: "string", - }, - }, - }, - excludeKeywords: { - type: "array", - items: { - type: "array", - items: { - type: "string", - }, - }, - }, - users: { - type: "array", - items: { - type: "string", - }, - }, - instances: { - type: "array", - items: { - type: "string", - }, - }, - caseSensitive: { type: "boolean" }, - withReplies: { type: "boolean" }, - withFile: { type: "boolean" }, - notify: { type: "boolean" }, - }, - required: [ - "name", - "src", - "keywords", - "excludeKeywords", - "users", - "instances", - "caseSensitive", - "withReplies", - "withFile", - "notify", - ], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - if (user.movedToUri != null) throw new ApiError(meta.errors.noSuchUserGroup); - let userList; - let userGroupJoining; - - if (ps.src === "list" && ps.userListId) { - userList = await UserLists.findOneBy({ - id: ps.userListId, - userId: user.id, - }); - - if (userList == null) { - throw new ApiError(meta.errors.noSuchUserList); - } - } else if (ps.src === "group" && ps.userGroupId) { - userGroupJoining = await UserGroupJoinings.findOneBy({ - userGroupId: ps.userGroupId, - userId: user.id, - }); - - if (userGroupJoining == null) { - throw new ApiError(meta.errors.noSuchUserGroup); - } - } - - const antenna = await Antennas.insert({ - id: genId(), - createdAt: new Date(), - userId: user.id, - name: ps.name, - src: ps.src, - userListId: userList ? userList.id : null, - userGroupJoiningId: userGroupJoining ? userGroupJoining.id : null, - keywords: ps.keywords, - excludeKeywords: ps.excludeKeywords, - users: ps.users, - instances: ps.instances, - caseSensitive: ps.caseSensitive, - withReplies: ps.withReplies, - withFile: ps.withFile, - notify: ps.notify, - }).then((x) => Antennas.findOneByOrFail(x.identifiers[0])); - - publishInternalEvent("antennaCreated", antenna); - - return await Antennas.pack(antenna); -}); diff --git a/packages/backend/src/server/api/endpoints/antennas/delete.ts b/packages/backend/src/server/api/endpoints/antennas/delete.ts deleted file mode 100644 index a6cf79011a..0000000000 --- a/packages/backend/src/server/api/endpoints/antennas/delete.ts +++ /dev/null @@ -1,43 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { Antennas } from "@/models/index.js"; -import { publishInternalEvent } from "@/services/stream.js"; - -export const meta = { - tags: ["antennas"], - - requireCredential: true, - - kind: "write:account", - - errors: { - noSuchAntenna: { - message: "No such antenna.", - code: "NO_SUCH_ANTENNA", - id: "b34dcf9d-348f-44bb-99d0-6c9314cfe2df", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - antennaId: { type: "string", format: "misskey:id" }, - }, - required: ["antennaId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const antenna = await Antennas.findOneBy({ - id: ps.antennaId, - userId: user.id, - }); - - if (antenna == null) { - throw new ApiError(meta.errors.noSuchAntenna); - } - - await Antennas.delete(antenna.id); - - publishInternalEvent("antennaDeleted", antenna); -}); diff --git a/packages/backend/src/server/api/endpoints/antennas/list.ts b/packages/backend/src/server/api/endpoints/antennas/list.ts deleted file mode 100644 index 929b761d4f..0000000000 --- a/packages/backend/src/server/api/endpoints/antennas/list.ts +++ /dev/null @@ -1,36 +0,0 @@ -import define from "../../define.js"; -import { Antennas } from "@/models/index.js"; - -export const meta = { - tags: ["antennas", "account"], - - requireCredential: true, - - kind: "read:account", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Antenna", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const antennas = await Antennas.findBy({ - userId: me.id, - }); - - return await Promise.all(antennas.map((x) => Antennas.pack(x))); -}); diff --git a/packages/backend/src/server/api/endpoints/antennas/markread.ts b/packages/backend/src/server/api/endpoints/antennas/markread.ts deleted file mode 100644 index e29e13bbbb..0000000000 --- a/packages/backend/src/server/api/endpoints/antennas/markread.ts +++ /dev/null @@ -1,43 +0,0 @@ -import define from "../../define.js"; -import { Antennas, AntennaNotes } from "@/models/index.js"; -import { FindOptionsWhere } from "typeorm"; -import { AntennaNote } from "@/models/entities/antenna-note.js"; - -export const meta = { - tags: ["antennas", "account"], - - requireCredential: true, - - kind: "write:account", -} as const; - -export const paramDef = { - type: "object", - properties: { - antennaId: { type: "string", format: "misskey:id" }, - }, - required: ["antennaId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const antenna = await Antennas.findOneBy({ - userId: me.id, - id: ps.antennaId, - }); - - if (!antenna) { - return null; - } - - await AntennaNotes.update( - { - antennaId: antenna.id, - read: false, - }, - { - read: true, - }, - ); - - return true; -}); diff --git a/packages/backend/src/server/api/endpoints/antennas/notes.ts b/packages/backend/src/server/api/endpoints/antennas/notes.ts deleted file mode 100644 index d011c5fb80..0000000000 --- a/packages/backend/src/server/api/endpoints/antennas/notes.ts +++ /dev/null @@ -1,97 +0,0 @@ -import define from "../../define.js"; -import readNote from "@/services/note/read.js"; -import { Antennas, Notes, AntennaNotes } from "@/models/index.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { generateVisibilityQuery } from "../../common/generate-visibility-query.js"; -import { generateMutedUserQuery } from "../../common/generate-muted-user-query.js"; -import { ApiError } from "../../error.js"; -import { generateBlockedUserQuery } from "../../common/generate-block-query.js"; - -export const meta = { - tags: ["antennas", "account", "notes"], - - requireCredential: true, - - kind: "read:account", - - errors: { - noSuchAntenna: { - message: "No such antenna.", - code: "NO_SUCH_ANTENNA", - id: "850926e0-fd3b-49b6-b69a-b28a5dbd82fe", - }, - }, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - antennaId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - sinceDate: { type: "integer" }, - untilDate: { type: "integer" }, - }, - required: ["antennaId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const antenna = await Antennas.findOneBy({ - id: ps.antennaId, - userId: user.id, - }); - - if (antenna == null) { - throw new ApiError(meta.errors.noSuchAntenna); - } - - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - ps.sinceId, - ps.untilId, - ps.sinceDate, - ps.untilDate, - ) - .innerJoin( - AntennaNotes.metadata.targetName, - "antennaNote", - "antennaNote.noteId = note.id", - ) - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner") - .andWhere("antennaNote.antennaId = :antennaId", { antennaId: antenna.id }); - - generateVisibilityQuery(query, user); - generateMutedUserQuery(query, user); - generateBlockedUserQuery(query, user); - - const notes = await query.take(ps.limit).getMany(); - - if (notes.length > 0) { - readNote(user.id, notes); - } - - return await Notes.packMany(notes, user); -}); diff --git a/packages/backend/src/server/api/endpoints/antennas/show.ts b/packages/backend/src/server/api/endpoints/antennas/show.ts deleted file mode 100644 index 350d739216..0000000000 --- a/packages/backend/src/server/api/endpoints/antennas/show.ts +++ /dev/null @@ -1,48 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { Antennas } from "@/models/index.js"; - -export const meta = { - tags: ["antennas", "account"], - - requireCredential: true, - - kind: "read:account", - - errors: { - noSuchAntenna: { - message: "No such antenna.", - code: "NO_SUCH_ANTENNA", - id: "c06569fb-b025-4f23-b22d-1fcd20d2816b", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "Antenna", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - antennaId: { type: "string", format: "misskey:id" }, - }, - required: ["antennaId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - // Fetch the antenna - const antenna = await Antennas.findOneBy({ - id: ps.antennaId, - userId: me.id, - }); - - if (antenna == null) { - throw new ApiError(meta.errors.noSuchAntenna); - } - - return await Antennas.pack(antenna); -}); diff --git a/packages/backend/src/server/api/endpoints/antennas/update.ts b/packages/backend/src/server/api/endpoints/antennas/update.ts deleted file mode 100644 index f491c0b638..0000000000 --- a/packages/backend/src/server/api/endpoints/antennas/update.ts +++ /dev/null @@ -1,157 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { Antennas, UserLists, UserGroupJoinings } from "@/models/index.js"; -import { publishInternalEvent } from "@/services/stream.js"; - -export const meta = { - tags: ["antennas"], - - requireCredential: true, - - kind: "write:account", - - errors: { - noSuchAntenna: { - message: "No such antenna.", - code: "NO_SUCH_ANTENNA", - id: "10c673ac-8852-48eb-aa1f-f5b67f069290", - }, - - noSuchUserList: { - message: "No such user list.", - code: "NO_SUCH_USER_LIST", - id: "1c6b35c9-943e-48c2-81e4-2844989407f7", - }, - - noSuchUserGroup: { - message: "No such user group.", - code: "NO_SUCH_USER_GROUP", - id: "109ed789-b6eb-456e-b8a9-6059d567d385", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "Antenna", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - antennaId: { type: "string", format: "misskey:id" }, - name: { type: "string", minLength: 1, maxLength: 100 }, - src: { - type: "string", - enum: ["home", "all", "users", "list", "group", "instances"], - }, - userListId: { type: "string", format: "misskey:id", nullable: true }, - userGroupId: { type: "string", format: "misskey:id", nullable: true }, - keywords: { - type: "array", - items: { - type: "array", - items: { - type: "string", - }, - }, - }, - excludeKeywords: { - type: "array", - items: { - type: "array", - items: { - type: "string", - }, - }, - }, - users: { - type: "array", - items: { - type: "string", - }, - }, - instances: { - type: "array", - items: { - type: "string", - }, - }, - caseSensitive: { type: "boolean" }, - withReplies: { type: "boolean" }, - withFile: { type: "boolean" }, - notify: { type: "boolean" }, - }, - required: [ - "antennaId", - "name", - "src", - "keywords", - "excludeKeywords", - "users", - "instances", - "caseSensitive", - "withReplies", - "withFile", - "notify", - ], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Fetch the antenna - const antenna = await Antennas.findOneBy({ - id: ps.antennaId, - userId: user.id, - }); - - if (antenna == null) { - throw new ApiError(meta.errors.noSuchAntenna); - } - - let userList; - let userGroupJoining; - - if (ps.src === "list" && ps.userListId) { - userList = await UserLists.findOneBy({ - id: ps.userListId, - userId: user.id, - }); - - if (userList == null) { - throw new ApiError(meta.errors.noSuchUserList); - } - } else if (ps.src === "group" && ps.userGroupId) { - userGroupJoining = await UserGroupJoinings.findOneBy({ - userGroupId: ps.userGroupId, - userId: user.id, - }); - - if (userGroupJoining == null) { - throw new ApiError(meta.errors.noSuchUserGroup); - } - } - - await Antennas.update(antenna.id, { - name: ps.name, - src: ps.src, - userListId: userList ? userList.id : null, - userGroupJoiningId: userGroupJoining ? userGroupJoining.id : null, - keywords: ps.keywords, - excludeKeywords: ps.excludeKeywords, - users: ps.users, - instances: ps.instances, - caseSensitive: ps.caseSensitive, - withReplies: ps.withReplies, - withFile: ps.withFile, - notify: ps.notify, - }); - - publishInternalEvent( - "antennaUpdated", - await Antennas.findOneByOrFail({ id: antenna.id }), - ); - - return await Antennas.pack(antenna.id); -}); diff --git a/packages/backend/src/server/api/endpoints/ap/get.ts b/packages/backend/src/server/api/endpoints/ap/get.ts deleted file mode 100644 index f0db67a343..0000000000 --- a/packages/backend/src/server/api/endpoints/ap/get.ts +++ /dev/null @@ -1,36 +0,0 @@ -import define from "../../define.js"; -import Resolver from "@/remote/activitypub/resolver.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - tags: ["federation"], - - requireCredential: true, - - limit: { - duration: HOUR, - max: 30, - }, - - errors: {}, - - res: { - type: "object", - optional: false, - nullable: false, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - uri: { type: "string" }, - }, - required: ["uri"], -} as const; - -export default define(meta, paramDef, async (ps) => { - const resolver = new Resolver(); - const object = await resolver.resolve(ps.uri); - return object; -}); diff --git a/packages/backend/src/server/api/endpoints/ap/show.ts b/packages/backend/src/server/api/endpoints/ap/show.ts deleted file mode 100644 index fa804802eb..0000000000 --- a/packages/backend/src/server/api/endpoints/ap/show.ts +++ /dev/null @@ -1,164 +0,0 @@ -import define from "../../define.js"; -import config from "@/config/index.js"; -import { createPerson } from "@/remote/activitypub/models/person.js"; -import { createNote } from "@/remote/activitypub/models/note.js"; -import DbResolver from "@/remote/activitypub/db-resolver.js"; -import Resolver from "@/remote/activitypub/resolver.js"; -import { ApiError } from "../../error.js"; -import { extractDbHost } from "@/misc/convert-host.js"; -import { Users, Notes } from "@/models/index.js"; -import type { Note } from "@/models/entities/note.js"; -import type { CacheableLocalUser, User } from "@/models/entities/user.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { isActor, isPost, getApId } from "@/remote/activitypub/type.js"; -import type { SchemaType } from "@/misc/schema.js"; -import { HOUR } from "@/const.js"; -import { shouldBlockInstance } from "@/misc/should-block-instance.js"; - -export const meta = { - tags: ["federation"], - - requireCredential: true, - - limit: { - duration: HOUR, - max: 30, - }, - - errors: { - noSuchObject: { - message: "No such object.", - code: "NO_SUCH_OBJECT", - id: "dc94d745-1262-4e63-a17d-fecaa57efc82", - }, - }, - - res: { - optional: false, - nullable: false, - oneOf: [ - { - type: "object", - properties: { - type: { - type: "string", - optional: false, - nullable: false, - enum: ["User"], - }, - object: { - type: "object", - optional: false, - nullable: false, - ref: "UserDetailedNotMe", - }, - }, - }, - { - type: "object", - properties: { - type: { - type: "string", - optional: false, - nullable: false, - enum: ["Note"], - }, - object: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, - }, - ], - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - uri: { type: "string" }, - }, - required: ["uri"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const object = await fetchAny(ps.uri, me); - if (object) { - return object; - } else { - throw new ApiError(meta.errors.noSuchObject); - } -}); - -/*** - * Resolve User or Note from URI - */ -async function fetchAny( - uri: string, - me: CacheableLocalUser | null | undefined, -): Promise<SchemaType<typeof meta["res"]> | null> { - // Wait if blocked. - if (await shouldBlockInstance(extractDbHost(uri))) return null; - - const dbResolver = new DbResolver(); - - let local = await mergePack( - me, - ...(await Promise.all([ - dbResolver.getUserFromApId(uri), - dbResolver.getNoteFromApId(uri), - ])), - ); - if (local != null) return local; - - // fetching Object once from remote - const resolver = new Resolver(); - const object = (await resolver.resolve(uri)) as any; - - // /@user If a URI other than the id is specified, - // the URI is determined here - if (uri !== object.id) { - local = await mergePack( - me, - ...(await Promise.all([ - dbResolver.getUserFromApId(object.id), - dbResolver.getNoteFromApId(object.id), - ])), - ); - if (local != null) return local; - } - - return await mergePack( - me, - isActor(object) ? await createPerson(getApId(object)) : null, - isPost(object) ? await createNote(getApId(object), undefined, true) : null, - ); -} - -async function mergePack( - me: CacheableLocalUser | null | undefined, - user: User | null | undefined, - note: Note | null | undefined, -): Promise<SchemaType<typeof meta.res> | null> { - if (user != null) { - return { - type: "User", - object: await Users.pack(user, me, { detail: true }), - }; - } else if (note != null) { - try { - const object = await Notes.pack(note, me, { detail: true }); - - return { - type: "Note", - object, - }; - } catch (e) { - return null; - } - } - - return null; -} diff --git a/packages/backend/src/server/api/endpoints/app/create.ts b/packages/backend/src/server/api/endpoints/app/create.ts deleted file mode 100644 index 013c5a10b9..0000000000 --- a/packages/backend/src/server/api/endpoints/app/create.ts +++ /dev/null @@ -1,67 +0,0 @@ -import define from "../../define.js"; -import { Apps } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import { unique } from "@/prelude/array.js"; -import { secureRndstr } from "@/misc/secure-rndstr.js"; - -export const meta = { - tags: ["app"], - - requireCredential: false, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "App", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - name: { type: "string" }, - description: { type: "string" }, - permission: { - type: "array", - uniqueItems: true, - items: { - type: "string", - }, - }, - callbackUrl: { type: "string", nullable: true }, - }, - required: ["name", "description", "permission"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - if (user?.movedToUri != null) - return await Apps.pack("", null, { - detail: true, - includeSecret: true, - }); - // Generate secret - const secret = secureRndstr(32, true); - - // for backward compatibility - const permission = unique( - ps.permission.map((v) => v.replace(/^(.+)(\/|-)(read|write)$/, "$3:$1")), - ); - - // Create account - const app = await Apps.insert({ - id: genId(), - createdAt: new Date(), - userId: user ? user.id : null, - name: ps.name, - description: ps.description, - permission, - callbackUrl: ps.callbackUrl, - secret: secret, - }).then((x) => Apps.findOneByOrFail(x.identifiers[0])); - - return await Apps.pack(app, null, { - detail: true, - includeSecret: true, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/app/show.ts b/packages/backend/src/server/api/endpoints/app/show.ts deleted file mode 100644 index 60949512e0..0000000000 --- a/packages/backend/src/server/api/endpoints/app/show.ts +++ /dev/null @@ -1,46 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { Apps } from "@/models/index.js"; - -export const meta = { - tags: ["app"], - - errors: { - noSuchApp: { - message: "No such app.", - code: "NO_SUCH_APP", - id: "dce83913-2dc6-4093-8a7b-71dbb11718a3", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "App", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - appId: { type: "string", format: "misskey:id" }, - }, - required: ["appId"], -} as const; - -export default define(meta, paramDef, async (ps, user, token) => { - const isSecure = user != null && token == null; - - // Lookup app - const ap = await Apps.findOneBy({ id: ps.appId }); - - if (ap == null) { - throw new ApiError(meta.errors.noSuchApp); - } - - return await Apps.pack(ap, user, { - detail: true, - includeSecret: isSecure && ap.userId === user!.id, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/auth/accept.ts b/packages/backend/src/server/api/endpoints/auth/accept.ts deleted file mode 100644 index 35565e2560..0000000000 --- a/packages/backend/src/server/api/endpoints/auth/accept.ts +++ /dev/null @@ -1,76 +0,0 @@ -import * as crypto from "node:crypto"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { AuthSessions, AccessTokens, Apps } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import { secureRndstr } from "@/misc/secure-rndstr.js"; - -export const meta = { - tags: ["auth"], - - requireCredential: true, - - secure: true, - - errors: { - noSuchSession: { - message: "No such session.", - code: "NO_SUCH_SESSION", - id: "9c72d8de-391a-43c1-9d06-08d29efde8df", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - token: { type: "string" }, - }, - required: ["token"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Fetch token - const session = await AuthSessions.findOneBy({ token: ps.token }); - - if (session == null) { - throw new ApiError(meta.errors.noSuchSession); - } - - // Generate access token - const accessToken = secureRndstr(32, true); - - // Fetch exist access token - const exist = await AccessTokens.findOneBy({ - appId: session.appId, - userId: user.id, - }); - - if (exist == null) { - // Lookup app - const app = await Apps.findOneByOrFail({ id: session.appId }); - - // Generate Hash - const sha256 = crypto.createHash("sha256"); - sha256.update(accessToken + app.secret); - const hash = sha256.digest("hex"); - - const now = new Date(); - - // Insert access token doc - await AccessTokens.insert({ - id: genId(), - createdAt: now, - lastUsedAt: now, - appId: session.appId, - userId: user.id, - token: accessToken, - hash: hash, - }); - } - - // Update session - await AuthSessions.update(session.id, { - userId: user.id, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/auth/session/generate.ts b/packages/backend/src/server/api/endpoints/auth/session/generate.ts deleted file mode 100644 index 1defb94006..0000000000 --- a/packages/backend/src/server/api/endpoints/auth/session/generate.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { v4 as uuid } from "uuid"; -import config from "@/config/index.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { Apps, AuthSessions } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; - -export const meta = { - tags: ["auth"], - - requireCredential: false, - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - token: { - type: "string", - optional: false, - nullable: false, - }, - url: { - type: "string", - optional: false, - nullable: false, - format: "url", - }, - }, - }, - - errors: { - noSuchApp: { - message: "No such app.", - code: "NO_SUCH_APP", - id: "92f93e63-428e-4f2f-a5a4-39e1407fe998", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - appSecret: { type: "string" }, - }, - required: ["appSecret"], -} as const; - -export default define(meta, paramDef, async (ps) => { - // Lookup app - const app = await Apps.findOneBy({ - secret: ps.appSecret, - }); - - if (app == null) { - throw new ApiError(meta.errors.noSuchApp); - } - - // Generate token - const token = uuid(); - - // Create session token document - const doc = await AuthSessions.insert({ - id: genId(), - createdAt: new Date(), - appId: app.id, - token: token, - }).then((x) => AuthSessions.findOneByOrFail(x.identifiers[0])); - - return { - token: doc.token, - url: `${config.authUrl}/${doc.token}`, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/auth/session/show.ts b/packages/backend/src/server/api/endpoints/auth/session/show.ts deleted file mode 100644 index 01a5fe5dc7..0000000000 --- a/packages/backend/src/server/api/endpoints/auth/session/show.ts +++ /dev/null @@ -1,63 +0,0 @@ -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { AuthSessions } from "@/models/index.js"; - -export const meta = { - tags: ["auth"], - - requireCredential: false, - - errors: { - noSuchSession: { - message: "No such session.", - code: "NO_SUCH_SESSION", - id: "bd72c97d-eba7-4adb-a467-f171b8847250", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - app: { - type: "object", - optional: false, - nullable: false, - ref: "App", - }, - token: { - type: "string", - optional: false, - nullable: false, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - token: { type: "string" }, - }, - required: ["token"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Lookup session - const session = await AuthSessions.findOneBy({ - token: ps.token, - }); - - if (session == null) { - throw new ApiError(meta.errors.noSuchSession); - } - - return await AuthSessions.pack(session, user); -}); diff --git a/packages/backend/src/server/api/endpoints/auth/session/userkey.ts b/packages/backend/src/server/api/endpoints/auth/session/userkey.ts deleted file mode 100644 index 0e97bf414e..0000000000 --- a/packages/backend/src/server/api/endpoints/auth/session/userkey.ts +++ /dev/null @@ -1,99 +0,0 @@ -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { Apps, AuthSessions, AccessTokens, Users } from "@/models/index.js"; - -export const meta = { - tags: ["auth"], - - requireCredential: false, - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - accessToken: { - type: "string", - optional: false, - nullable: false, - }, - - user: { - type: "object", - optional: false, - nullable: false, - ref: "UserDetailedNotMe", - }, - }, - }, - - errors: { - noSuchApp: { - message: "No such app.", - code: "NO_SUCH_APP", - id: "fcab192a-2c5a-43b7-8ad8-9b7054d8d40d", - }, - - noSuchSession: { - message: "No such session.", - code: "NO_SUCH_SESSION", - id: "5b5a1503-8bc8-4bd0-8054-dc189e8cdcb3", - }, - - pendingSession: { - message: "This session is not completed yet.", - code: "PENDING_SESSION", - id: "8c8a4145-02cc-4cca-8e66-29ba60445a8e", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - appSecret: { type: "string" }, - token: { type: "string" }, - }, - required: ["appSecret", "token"], -} as const; - -export default define(meta, paramDef, async (ps) => { - // Lookup app - const app = await Apps.findOneBy({ - secret: ps.appSecret, - }); - - if (app == null) { - throw new ApiError(meta.errors.noSuchApp); - } - - // Fetch token - const session = await AuthSessions.findOneBy({ - token: ps.token, - appId: app.id, - }); - - if (session == null) { - throw new ApiError(meta.errors.noSuchSession); - } - - if (session.userId == null) { - throw new ApiError(meta.errors.pendingSession); - } - - // Lookup access token - const accessToken = await AccessTokens.findOneByOrFail({ - appId: app.id, - userId: session.userId, - }); - - // Delete session - AuthSessions.delete(session.id); - - return { - accessToken: accessToken.token, - user: await Users.pack(session.userId, null, { - detail: true, - }), - }; -}); diff --git a/packages/backend/src/server/api/endpoints/blocking/create.ts b/packages/backend/src/server/api/endpoints/blocking/create.ts deleted file mode 100644 index 4bd58d5ef5..0000000000 --- a/packages/backend/src/server/api/endpoints/blocking/create.ts +++ /dev/null @@ -1,91 +0,0 @@ -import create from "@/services/blocking/create.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { getUser } from "../../common/getters.js"; -import { Blockings, NoteWatchings, Users } from "@/models/index.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - tags: ["account"], - - limit: { - duration: HOUR, - max: 100, - }, - - requireCredential: true, - - kind: "write:blocks", - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "7cc4f851-e2f1-4621-9633-ec9e1d00c01e", - }, - - blockeeIsYourself: { - message: "Blockee is yourself.", - code: "BLOCKEE_IS_YOURSELF", - id: "88b19138-f28d-42c0-8499-6a31bbd0fdc6", - }, - - alreadyBlocking: { - message: "You are already blocking that user.", - code: "ALREADY_BLOCKING", - id: "787fed64-acb9-464a-82eb-afbd745b9614", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "UserDetailedNotMe", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const blocker = await Users.findOneByOrFail({ id: user.id }); - - // 自分自身 - if (user.id === ps.userId) { - throw new ApiError(meta.errors.blockeeIsYourself); - } - - // Get blockee - const blockee = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - // Check if already blocking - const exist = await Blockings.findOneBy({ - blockerId: blocker.id, - blockeeId: blockee.id, - }); - - if (exist != null) { - throw new ApiError(meta.errors.alreadyBlocking); - } - - await create(blocker, blockee); - - NoteWatchings.delete({ - userId: blocker.id, - noteUserId: blockee.id, - }); - - return await Users.pack(blockee.id, blocker, { - detail: true, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/blocking/delete.ts b/packages/backend/src/server/api/endpoints/blocking/delete.ts deleted file mode 100644 index 6c4ca27755..0000000000 --- a/packages/backend/src/server/api/endpoints/blocking/delete.ts +++ /dev/null @@ -1,87 +0,0 @@ -import deleteBlocking from "@/services/blocking/delete.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { getUser } from "../../common/getters.js"; -import { Blockings, Users } from "@/models/index.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - tags: ["account"], - - limit: { - duration: HOUR, - max: 100, - }, - - requireCredential: true, - - kind: "write:blocks", - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "8621d8bf-c358-4303-a066-5ea78610eb3f", - }, - - blockeeIsYourself: { - message: "Blockee is yourself.", - code: "BLOCKEE_IS_YOURSELF", - id: "06f6fac6-524b-473c-a354-e97a40ae6eac", - }, - - notBlocking: { - message: "You are not blocking that user.", - code: "NOT_BLOCKING", - id: "291b2efa-60c6-45c0-9f6a-045c8f9b02cd", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "UserDetailedNotMe", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const blocker = await Users.findOneByOrFail({ id: user.id }); - - // Check if the blockee is yourself - if (user.id === ps.userId) { - throw new ApiError(meta.errors.blockeeIsYourself); - } - - // Get blockee - const blockee = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - // Check not blocking - const exist = await Blockings.findOneBy({ - blockerId: blocker.id, - blockeeId: blockee.id, - }); - - if (exist == null) { - throw new ApiError(meta.errors.notBlocking); - } - - // Delete blocking - await deleteBlocking(blocker, blockee); - - return await Users.pack(blockee.id, blocker, { - detail: true, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/blocking/list.ts b/packages/backend/src/server/api/endpoints/blocking/list.ts deleted file mode 100644 index 83fca7b42c..0000000000 --- a/packages/backend/src/server/api/endpoints/blocking/list.ts +++ /dev/null @@ -1,45 +0,0 @@ -import define from "../../define.js"; -import { Blockings } from "@/models/index.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["account"], - - requireCredential: true, - - kind: "read:blocks", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Blocking", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 30 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = makePaginationQuery( - Blockings.createQueryBuilder("blocking"), - ps.sinceId, - ps.untilId, - ).andWhere("blocking.blockerId = :meId", { meId: me.id }); - - const blockings = await query.take(ps.limit).getMany(); - - return await Blockings.packMany(blockings, me); -}); diff --git a/packages/backend/src/server/api/endpoints/channels/create.ts b/packages/backend/src/server/api/endpoints/channels/create.ts deleted file mode 100644 index 26a3448b2b..0000000000 --- a/packages/backend/src/server/api/endpoints/channels/create.ts +++ /dev/null @@ -1,68 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { Channels, DriveFiles } from "@/models/index.js"; -import type { Channel } from "@/models/entities/channel.js"; -import { genId } from "@/misc/gen-id.js"; - -export const meta = { - tags: ["channels"], - - requireCredential: true, - - kind: "write:channels", - - res: { - type: "object", - optional: false, - nullable: false, - ref: "Channel", - }, - - errors: { - noSuchFile: { - message: "No such file.", - code: "NO_SUCH_FILE", - id: "cd1e9f3e-5a12-4ab4-96f6-5d0a2cc32050", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - name: { type: "string", minLength: 1, maxLength: 128 }, - description: { - type: "string", - nullable: true, - minLength: 1, - maxLength: 2048, - }, - bannerId: { type: "string", format: "misskey:id", nullable: true }, - }, - required: ["name"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - let banner = null; - if (ps.bannerId != null) { - banner = await DriveFiles.findOneBy({ - id: ps.bannerId, - userId: user.id, - }); - - if (banner == null) { - throw new ApiError(meta.errors.noSuchFile); - } - } - - const channel = await Channels.insert({ - id: genId(), - createdAt: new Date(), - userId: user.id, - name: ps.name, - description: ps.description || null, - bannerId: banner ? banner.id : null, - } as Channel).then((x) => Channels.findOneByOrFail(x.identifiers[0])); - - return await Channels.pack(channel, user); -}); diff --git a/packages/backend/src/server/api/endpoints/channels/featured.ts b/packages/backend/src/server/api/endpoints/channels/featured.ts deleted file mode 100644 index 06e0e850fd..0000000000 --- a/packages/backend/src/server/api/endpoints/channels/featured.ts +++ /dev/null @@ -1,37 +0,0 @@ -import define from "../../define.js"; -import { Channels } from "@/models/index.js"; - -export const meta = { - tags: ["channels"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Channel", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = Channels.createQueryBuilder("channel") - .where("channel.lastNotedAt IS NOT NULL") - .orderBy("channel.lastNotedAt", "DESC"); - - const channels = await query.take(10).getMany(); - - return await Promise.all(channels.map((x) => Channels.pack(x, me))); -}); diff --git a/packages/backend/src/server/api/endpoints/channels/follow.ts b/packages/backend/src/server/api/endpoints/channels/follow.ts deleted file mode 100644 index de0554383e..0000000000 --- a/packages/backend/src/server/api/endpoints/channels/follow.ts +++ /dev/null @@ -1,48 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { Channels, ChannelFollowings } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import { publishUserEvent } from "@/services/stream.js"; - -export const meta = { - tags: ["channels"], - - requireCredential: true, - - kind: "write:channels", - - errors: { - noSuchChannel: { - message: "No such channel.", - code: "NO_SUCH_CHANNEL", - id: "c0031718-d573-4e85-928e-10039f1fbb68", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - channelId: { type: "string", format: "misskey:id" }, - }, - required: ["channelId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const channel = await Channels.findOneBy({ - id: ps.channelId, - }); - - if (channel == null) { - throw new ApiError(meta.errors.noSuchChannel); - } - - await ChannelFollowings.insert({ - id: genId(), - createdAt: new Date(), - followerId: user.id, - followeeId: channel.id, - }); - - publishUserEvent(user.id, "followChannel", channel); -}); diff --git a/packages/backend/src/server/api/endpoints/channels/followed.ts b/packages/backend/src/server/api/endpoints/channels/followed.ts deleted file mode 100644 index 993a211f7e..0000000000 --- a/packages/backend/src/server/api/endpoints/channels/followed.ts +++ /dev/null @@ -1,59 +0,0 @@ -import define from "../../define.js"; -import { Channels, ChannelFollowings } from "@/models/index.js"; - -export const meta = { - tags: ["channels", "account"], - - requireCredential: true, - - kind: "read:channels", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Channel", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 5 }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = ChannelFollowings.createQueryBuilder("following").andWhere({ - followerId: me.id, - }); - if (ps.sinceId) { - query.andWhere('following."followeeId" > :sinceId', { - sinceId: ps.sinceId, - }); - } - if (ps.untilId) { - query.andWhere('following."followeeId" < :untilId', { - untilId: ps.untilId, - }); - } - if (ps.sinceId && !ps.untilId) { - query.orderBy('following."followeeId"', "ASC"); - } else { - query.orderBy('following."followeeId"', "DESC"); - } - - const followings = await query.take(ps.limit).getMany(); - - return await Promise.all( - followings.map((x) => Channels.pack(x.followeeId, me)), - ); -}); diff --git a/packages/backend/src/server/api/endpoints/channels/owned.ts b/packages/backend/src/server/api/endpoints/channels/owned.ts deleted file mode 100644 index 78d9e80ccf..0000000000 --- a/packages/backend/src/server/api/endpoints/channels/owned.ts +++ /dev/null @@ -1,45 +0,0 @@ -import define from "../../define.js"; -import { Channels } from "@/models/index.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["channels", "account"], - - requireCredential: true, - - kind: "read:channels", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Channel", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 5 }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = makePaginationQuery( - Channels.createQueryBuilder(), - ps.sinceId, - ps.untilId, - ).andWhere({ userId: me.id }); - - const channels = await query.take(ps.limit).getMany(); - - return await Promise.all(channels.map((x) => Channels.pack(x, me))); -}); diff --git a/packages/backend/src/server/api/endpoints/channels/show.ts b/packages/backend/src/server/api/endpoints/channels/show.ts deleted file mode 100644 index e4ca756634..0000000000 --- a/packages/backend/src/server/api/endpoints/channels/show.ts +++ /dev/null @@ -1,45 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { Channels } from "@/models/index.js"; - -export const meta = { - tags: ["channels"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "Channel", - }, - - errors: { - noSuchChannel: { - message: "No such channel.", - code: "NO_SUCH_CHANNEL", - id: "6f6c314b-7486-4897-8966-c04a66a02923", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - channelId: { type: "string", format: "misskey:id" }, - }, - required: ["channelId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const channel = await Channels.findOneBy({ - id: ps.channelId, - }); - - if (channel == null) { - throw new ApiError(meta.errors.noSuchChannel); - } - - return await Channels.pack(channel, me); -}); diff --git a/packages/backend/src/server/api/endpoints/channels/timeline.ts b/packages/backend/src/server/api/endpoints/channels/timeline.ts deleted file mode 100644 index b5d5325234..0000000000 --- a/packages/backend/src/server/api/endpoints/channels/timeline.ts +++ /dev/null @@ -1,84 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { Notes, Channels } from "@/models/index.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { activeUsersChart } from "@/services/chart/index.js"; - -export const meta = { - tags: ["notes", "channels"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, - - errors: { - noSuchChannel: { - message: "No such channel.", - code: "NO_SUCH_CHANNEL", - id: "4d0eeeba-a02c-4c3c-9966-ef60d38d2e7f", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - channelId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - sinceDate: { type: "integer" }, - untilDate: { type: "integer" }, - }, - required: ["channelId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const channel = await Channels.findOneBy({ - id: ps.channelId, - }); - - if (channel == null) { - throw new ApiError(meta.errors.noSuchChannel); - } - - //#region Construct query - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - ps.sinceId, - ps.untilId, - ps.sinceDate, - ps.untilDate, - ) - .andWhere("note.channelId = :channelId", { channelId: channel.id }) - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner") - .leftJoinAndSelect("note.channel", "channel"); - //#endregion - - const timeline = await query.take(ps.limit).getMany(); - - if (user) activeUsersChart.read(user); - - return await Notes.packMany(timeline, user); -}); diff --git a/packages/backend/src/server/api/endpoints/channels/unfollow.ts b/packages/backend/src/server/api/endpoints/channels/unfollow.ts deleted file mode 100644 index 654a4fbba5..0000000000 --- a/packages/backend/src/server/api/endpoints/channels/unfollow.ts +++ /dev/null @@ -1,45 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { Channels, ChannelFollowings } from "@/models/index.js"; -import { publishUserEvent } from "@/services/stream.js"; - -export const meta = { - tags: ["channels"], - - requireCredential: true, - - kind: "write:channels", - - errors: { - noSuchChannel: { - message: "No such channel.", - code: "NO_SUCH_CHANNEL", - id: "19959ee9-0153-4c51-bbd9-a98c49dc59d6", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - channelId: { type: "string", format: "misskey:id" }, - }, - required: ["channelId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const channel = await Channels.findOneBy({ - id: ps.channelId, - }); - - if (channel == null) { - throw new ApiError(meta.errors.noSuchChannel); - } - - await ChannelFollowings.delete({ - followerId: user.id, - followeeId: channel.id, - }); - - publishUserEvent(user.id, "unfollowChannel", channel); -}); diff --git a/packages/backend/src/server/api/endpoints/channels/update.ts b/packages/backend/src/server/api/endpoints/channels/update.ts deleted file mode 100644 index d9f6f7644c..0000000000 --- a/packages/backend/src/server/api/endpoints/channels/update.ts +++ /dev/null @@ -1,90 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { Channels, DriveFiles } from "@/models/index.js"; - -export const meta = { - tags: ["channels"], - - requireCredential: true, - - kind: "write:channels", - - res: { - type: "object", - optional: false, - nullable: false, - ref: "Channel", - }, - - errors: { - noSuchChannel: { - message: "No such channel.", - code: "NO_SUCH_CHANNEL", - id: "f9c5467f-d492-4c3c-9a8d-a70dacc86512", - }, - - accessDenied: { - message: "You do not have edit privilege of the channel.", - code: "ACCESS_DENIED", - id: "1fb7cb09-d46a-4fdf-b8df-057788cce513", - }, - - noSuchFile: { - message: "No such file.", - code: "NO_SUCH_FILE", - id: "e86c14a4-0da2-4032-8df3-e737a04c7f3b", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - channelId: { type: "string", format: "misskey:id" }, - name: { type: "string", minLength: 1, maxLength: 128 }, - description: { - type: "string", - nullable: true, - minLength: 1, - maxLength: 2048, - }, - bannerId: { type: "string", format: "misskey:id", nullable: true }, - }, - required: ["channelId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const channel = await Channels.findOneBy({ - id: ps.channelId, - }); - - if (channel == null) { - throw new ApiError(meta.errors.noSuchChannel); - } - - if (channel.userId !== me.id) { - throw new ApiError(meta.errors.accessDenied); - } - - let banner = undefined; - if (ps.bannerId != null) { - banner = await DriveFiles.findOneBy({ - id: ps.bannerId, - userId: me.id, - }); - - if (banner == null) { - throw new ApiError(meta.errors.noSuchFile); - } - } else if (ps.bannerId === null) { - banner = null; - } - - await Channels.update(channel.id, { - ...(ps.name !== undefined ? { name: ps.name } : {}), - ...(ps.description !== undefined ? { description: ps.description } : {}), - ...(banner ? { bannerId: banner.id } : {}), - }); - - return await Channels.pack(channel.id, me); -}); diff --git a/packages/backend/src/server/api/endpoints/charts/active-users.ts b/packages/backend/src/server/api/endpoints/charts/active-users.ts deleted file mode 100644 index 3817a32ca9..0000000000 --- a/packages/backend/src/server/api/endpoints/charts/active-users.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { getJsonSchema } from "@/services/chart/core.js"; -import { activeUsersChart } from "@/services/chart/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["charts", "users"], - requireCredentialPrivateMode: true, - - res: getJsonSchema(activeUsersChart.schema), - - allowGet: true, - cacheSec: 60 * 60, -} as const; - -export const paramDef = { - type: "object", - properties: { - span: { type: "string", enum: ["day", "hour"] }, - limit: { type: "integer", minimum: 1, maximum: 500, default: 30 }, - offset: { type: "integer", nullable: true, default: null }, - }, - required: ["span"], -} as const; - -export default define(meta, paramDef, async (ps) => { - return await activeUsersChart.getChart( - ps.span, - ps.limit, - ps.offset ? new Date(ps.offset) : null, - ); -}); diff --git a/packages/backend/src/server/api/endpoints/charts/ap-request.ts b/packages/backend/src/server/api/endpoints/charts/ap-request.ts deleted file mode 100644 index 9e9013ce53..0000000000 --- a/packages/backend/src/server/api/endpoints/charts/ap-request.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { getJsonSchema } from "@/services/chart/core.js"; -import { apRequestChart } from "@/services/chart/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["charts"], - requireCredentialPrivateMode: true, - - res: getJsonSchema(apRequestChart.schema), - - allowGet: true, - cacheSec: 60 * 60, -} as const; - -export const paramDef = { - type: "object", - properties: { - span: { type: "string", enum: ["day", "hour"] }, - limit: { type: "integer", minimum: 1, maximum: 500, default: 30 }, - offset: { type: "integer", nullable: true, default: null }, - }, - required: ["span"], -} as const; - -export default define(meta, paramDef, async (ps) => { - return await apRequestChart.getChart( - ps.span, - ps.limit, - ps.offset ? new Date(ps.offset) : null, - ); -}); diff --git a/packages/backend/src/server/api/endpoints/charts/drive.ts b/packages/backend/src/server/api/endpoints/charts/drive.ts deleted file mode 100644 index 03ac4c0473..0000000000 --- a/packages/backend/src/server/api/endpoints/charts/drive.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { getJsonSchema } from "@/services/chart/core.js"; -import { driveChart } from "@/services/chart/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["charts", "drive"], - requireCredentialPrivateMode: true, - - res: getJsonSchema(driveChart.schema), - - allowGet: true, - cacheSec: 60 * 60, -} as const; - -export const paramDef = { - type: "object", - properties: { - span: { type: "string", enum: ["day", "hour"] }, - limit: { type: "integer", minimum: 1, maximum: 500, default: 30 }, - offset: { type: "integer", nullable: true, default: null }, - }, - required: ["span"], -} as const; - -export default define(meta, paramDef, async (ps) => { - return await driveChart.getChart( - ps.span, - ps.limit, - ps.offset ? new Date(ps.offset) : null, - ); -}); diff --git a/packages/backend/src/server/api/endpoints/charts/federation.ts b/packages/backend/src/server/api/endpoints/charts/federation.ts deleted file mode 100644 index 5862aad56e..0000000000 --- a/packages/backend/src/server/api/endpoints/charts/federation.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { getJsonSchema } from "@/services/chart/core.js"; -import { federationChart } from "@/services/chart/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["charts"], - requireCredentialPrivateMode: true, - - res: getJsonSchema(federationChart.schema), - - allowGet: true, - cacheSec: 60 * 60, -} as const; - -export const paramDef = { - type: "object", - properties: { - span: { type: "string", enum: ["day", "hour"] }, - limit: { type: "integer", minimum: 1, maximum: 500, default: 30 }, - offset: { type: "integer", nullable: true, default: null }, - }, - required: ["span"], -} as const; - -export default define(meta, paramDef, async (ps) => { - return await federationChart.getChart( - ps.span, - ps.limit, - ps.offset ? new Date(ps.offset) : null, - ); -}); diff --git a/packages/backend/src/server/api/endpoints/charts/hashtag.ts b/packages/backend/src/server/api/endpoints/charts/hashtag.ts deleted file mode 100644 index 0af1e35ea9..0000000000 --- a/packages/backend/src/server/api/endpoints/charts/hashtag.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { getJsonSchema } from "@/services/chart/core.js"; -import { hashtagChart } from "@/services/chart/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["charts", "hashtags"], - requireCredentialPrivateMode: true, - - res: getJsonSchema(hashtagChart.schema), - - allowGet: true, - cacheSec: 60 * 60, -} as const; - -export const paramDef = { - type: "object", - properties: { - span: { type: "string", enum: ["day", "hour"] }, - limit: { type: "integer", minimum: 1, maximum: 500, default: 30 }, - offset: { type: "integer", nullable: true, default: null }, - tag: { type: "string" }, - }, - required: ["span", "tag"], -} as const; - -export default define(meta, paramDef, async (ps) => { - return await hashtagChart.getChart( - ps.span, - ps.limit, - ps.offset ? new Date(ps.offset) : null, - ps.tag, - ); -}); diff --git a/packages/backend/src/server/api/endpoints/charts/instance.ts b/packages/backend/src/server/api/endpoints/charts/instance.ts deleted file mode 100644 index 11a1dbce1b..0000000000 --- a/packages/backend/src/server/api/endpoints/charts/instance.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { getJsonSchema } from "@/services/chart/core.js"; -import { instanceChart } from "@/services/chart/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["charts"], - requireCredentialPrivateMode: true, - - res: getJsonSchema(instanceChart.schema), - - allowGet: true, - cacheSec: 60 * 60, -} as const; - -export const paramDef = { - type: "object", - properties: { - span: { type: "string", enum: ["day", "hour"] }, - limit: { type: "integer", minimum: 1, maximum: 500, default: 30 }, - offset: { type: "integer", nullable: true, default: null }, - host: { type: "string" }, - }, - required: ["span", "host"], -} as const; - -export default define(meta, paramDef, async (ps) => { - return await instanceChart.getChart( - ps.span, - ps.limit, - ps.offset ? new Date(ps.offset) : null, - ps.host, - ); -}); diff --git a/packages/backend/src/server/api/endpoints/charts/notes.ts b/packages/backend/src/server/api/endpoints/charts/notes.ts deleted file mode 100644 index 27e69a4c9b..0000000000 --- a/packages/backend/src/server/api/endpoints/charts/notes.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { getJsonSchema } from "@/services/chart/core.js"; -import { notesChart } from "@/services/chart/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["charts", "notes"], - requireCredentialPrivateMode: true, - - res: getJsonSchema(notesChart.schema), - - allowGet: true, - cacheSec: 60 * 60, -} as const; - -export const paramDef = { - type: "object", - properties: { - span: { type: "string", enum: ["day", "hour"] }, - limit: { type: "integer", minimum: 1, maximum: 500, default: 30 }, - offset: { type: "integer", nullable: true, default: null }, - }, - required: ["span"], -} as const; - -export default define(meta, paramDef, async (ps) => { - return await notesChart.getChart( - ps.span, - ps.limit, - ps.offset ? new Date(ps.offset) : null, - ); -}); diff --git a/packages/backend/src/server/api/endpoints/charts/user/drive.ts b/packages/backend/src/server/api/endpoints/charts/user/drive.ts deleted file mode 100644 index 178ba453c6..0000000000 --- a/packages/backend/src/server/api/endpoints/charts/user/drive.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { getJsonSchema } from "@/services/chart/core.js"; -import { perUserDriveChart } from "@/services/chart/index.js"; -import define from "../../../define.js"; - -export const meta = { - tags: ["charts", "drive", "users"], - requireCredentialPrivateMode: true, - - res: getJsonSchema(perUserDriveChart.schema), - - allowGet: true, - cacheSec: 60 * 60, -} as const; - -export const paramDef = { - type: "object", - properties: { - span: { type: "string", enum: ["day", "hour"] }, - limit: { type: "integer", minimum: 1, maximum: 500, default: 30 }, - offset: { type: "integer", nullable: true, default: null }, - userId: { type: "string", format: "misskey:id" }, - }, - required: ["span", "userId"], -} as const; - -export default define(meta, paramDef, async (ps) => { - return await perUserDriveChart.getChart( - ps.span, - ps.limit, - ps.offset ? new Date(ps.offset) : null, - ps.userId, - ); -}); diff --git a/packages/backend/src/server/api/endpoints/charts/user/following.ts b/packages/backend/src/server/api/endpoints/charts/user/following.ts deleted file mode 100644 index 6a0c22df11..0000000000 --- a/packages/backend/src/server/api/endpoints/charts/user/following.ts +++ /dev/null @@ -1,33 +0,0 @@ -import define from "../../../define.js"; -import { getJsonSchema } from "@/services/chart/core.js"; -import { perUserFollowingChart } from "@/services/chart/index.js"; - -export const meta = { - tags: ["charts", "users", "following"], - requireCredentialPrivateMode: true, - - res: getJsonSchema(perUserFollowingChart.schema), - - allowGet: true, - cacheSec: 60 * 60, -} as const; - -export const paramDef = { - type: "object", - properties: { - span: { type: "string", enum: ["day", "hour"] }, - limit: { type: "integer", minimum: 1, maximum: 500, default: 30 }, - offset: { type: "integer", nullable: true, default: null }, - userId: { type: "string", format: "misskey:id" }, - }, - required: ["span", "userId"], -} as const; - -export default define(meta, paramDef, async (ps) => { - return await perUserFollowingChart.getChart( - ps.span, - ps.limit, - ps.offset ? new Date(ps.offset) : null, - ps.userId, - ); -}); diff --git a/packages/backend/src/server/api/endpoints/charts/user/notes.ts b/packages/backend/src/server/api/endpoints/charts/user/notes.ts deleted file mode 100644 index d788076962..0000000000 --- a/packages/backend/src/server/api/endpoints/charts/user/notes.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { getJsonSchema } from "@/services/chart/core.js"; -import { perUserNotesChart } from "@/services/chart/index.js"; -import define from "../../../define.js"; - -export const meta = { - tags: ["charts", "users", "notes"], - requireCredentialPrivateMode: true, - - res: getJsonSchema(perUserNotesChart.schema), - - allowGet: true, - cacheSec: 60 * 60, -} as const; - -export const paramDef = { - type: "object", - properties: { - span: { type: "string", enum: ["day", "hour"] }, - limit: { type: "integer", minimum: 1, maximum: 500, default: 30 }, - offset: { type: "integer", nullable: true, default: null }, - userId: { type: "string", format: "misskey:id" }, - }, - required: ["span", "userId"], -} as const; - -export default define(meta, paramDef, async (ps) => { - return await perUserNotesChart.getChart( - ps.span, - ps.limit, - ps.offset ? new Date(ps.offset) : null, - ps.userId, - ); -}); diff --git a/packages/backend/src/server/api/endpoints/charts/user/reactions.ts b/packages/backend/src/server/api/endpoints/charts/user/reactions.ts deleted file mode 100644 index 5b0048c50e..0000000000 --- a/packages/backend/src/server/api/endpoints/charts/user/reactions.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { getJsonSchema } from "@/services/chart/core.js"; -import { perUserReactionsChart } from "@/services/chart/index.js"; -import define from "../../../define.js"; - -export const meta = { - tags: ["charts", "users", "reactions"], - requireCredentialPrivateMode: true, - - res: getJsonSchema(perUserReactionsChart.schema), - - allowGet: true, - cacheSec: 60 * 60, -} as const; - -export const paramDef = { - type: "object", - properties: { - span: { type: "string", enum: ["day", "hour"] }, - limit: { type: "integer", minimum: 1, maximum: 500, default: 30 }, - offset: { type: "integer", nullable: true, default: null }, - userId: { type: "string", format: "misskey:id" }, - }, - required: ["span", "userId"], -} as const; - -export default define(meta, paramDef, async (ps) => { - return await perUserReactionsChart.getChart( - ps.span, - ps.limit, - ps.offset ? new Date(ps.offset) : null, - ps.userId, - ); -}); diff --git a/packages/backend/src/server/api/endpoints/charts/users.ts b/packages/backend/src/server/api/endpoints/charts/users.ts deleted file mode 100644 index 8973f013b7..0000000000 --- a/packages/backend/src/server/api/endpoints/charts/users.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { getJsonSchema } from "@/services/chart/core.js"; -import { usersChart } from "@/services/chart/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["charts", "users"], - requireCredentialPrivateMode: true, - - res: getJsonSchema(usersChart.schema), - - allowGet: true, - cacheSec: 60 * 60, -} as const; - -export const paramDef = { - type: "object", - properties: { - span: { type: "string", enum: ["day", "hour"] }, - limit: { type: "integer", minimum: 1, maximum: 500, default: 30 }, - offset: { type: "integer", nullable: true, default: null }, - }, - required: ["span"], -} as const; - -export default define(meta, paramDef, async (ps) => { - return await usersChart.getChart( - ps.span, - ps.limit, - ps.offset ? new Date(ps.offset) : null, - ); -}); diff --git a/packages/backend/src/server/api/endpoints/clips/add-note.ts b/packages/backend/src/server/api/endpoints/clips/add-note.ts deleted file mode 100644 index b9d6b54c95..0000000000 --- a/packages/backend/src/server/api/endpoints/clips/add-note.ts +++ /dev/null @@ -1,74 +0,0 @@ -import define from "../../define.js"; -import { ClipNotes, Clips } from "@/models/index.js"; -import { ApiError } from "../../error.js"; -import { genId } from "@/misc/gen-id.js"; -import { getNote } from "../../common/getters.js"; - -export const meta = { - tags: ["account", "notes", "clips"], - - requireCredential: true, - - kind: "write:account", - - errors: { - noSuchClip: { - message: "No such clip.", - code: "NO_SUCH_CLIP", - id: "d6e76cc0-a1b5-4c7c-a287-73fa9c716dcf", - }, - - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "fc8c0b49-c7a3-4664-a0a6-b418d386bb8b", - }, - - alreadyClipped: { - message: "The note has already been clipped.", - code: "ALREADY_CLIPPED", - id: "734806c4-542c-463a-9311-15c512803965", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - clipId: { type: "string", format: "misskey:id" }, - noteId: { type: "string", format: "misskey:id" }, - }, - required: ["clipId", "noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const clip = await Clips.findOneBy({ - id: ps.clipId, - userId: user.id, - }); - - if (clip == null) { - throw new ApiError(meta.errors.noSuchClip); - } - - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - const exist = await ClipNotes.findOneBy({ - noteId: note.id, - clipId: clip.id, - }); - - if (exist != null) { - throw new ApiError(meta.errors.alreadyClipped); - } - - await ClipNotes.insert({ - id: genId(), - noteId: note.id, - clipId: clip.id, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/clips/create.ts b/packages/backend/src/server/api/endpoints/clips/create.ts deleted file mode 100644 index 918e9462a4..0000000000 --- a/packages/backend/src/server/api/endpoints/clips/create.ts +++ /dev/null @@ -1,46 +0,0 @@ -import define from "../../define.js"; -import { genId } from "@/misc/gen-id.js"; -import { Clips } from "@/models/index.js"; - -export const meta = { - tags: ["clips"], - - requireCredential: true, - - kind: "write:account", - - res: { - type: "object", - optional: false, - nullable: false, - ref: "Clip", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - name: { type: "string", minLength: 1, maxLength: 100 }, - isPublic: { type: "boolean", default: false }, - description: { - type: "string", - nullable: true, - minLength: 1, - maxLength: 2048, - }, - }, - required: ["name"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const clip = await Clips.insert({ - id: genId(), - createdAt: new Date(), - userId: user.id, - name: ps.name, - isPublic: ps.isPublic, - description: ps.description, - }).then((x) => Clips.findOneByOrFail(x.identifiers[0])); - - return await Clips.pack(clip); -}); diff --git a/packages/backend/src/server/api/endpoints/clips/delete.ts b/packages/backend/src/server/api/endpoints/clips/delete.ts deleted file mode 100644 index 8f2489dddd..0000000000 --- a/packages/backend/src/server/api/endpoints/clips/delete.ts +++ /dev/null @@ -1,40 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { Clips } from "@/models/index.js"; - -export const meta = { - tags: ["clips"], - - requireCredential: true, - - kind: "write:account", - - errors: { - noSuchClip: { - message: "No such clip.", - code: "NO_SUCH_CLIP", - id: "70ca08ba-6865-4630-b6fb-8494759aa754", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - clipId: { type: "string", format: "misskey:id" }, - }, - required: ["clipId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const clip = await Clips.findOneBy({ - id: ps.clipId, - userId: user.id, - }); - - if (clip == null) { - throw new ApiError(meta.errors.noSuchClip); - } - - await Clips.delete(clip.id); -}); diff --git a/packages/backend/src/server/api/endpoints/clips/list.ts b/packages/backend/src/server/api/endpoints/clips/list.ts deleted file mode 100644 index d1625ee036..0000000000 --- a/packages/backend/src/server/api/endpoints/clips/list.ts +++ /dev/null @@ -1,36 +0,0 @@ -import define from "../../define.js"; -import { Clips } from "@/models/index.js"; - -export const meta = { - tags: ["clips", "account"], - - requireCredential: true, - - kind: "read:account", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Clip", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const clips = await Clips.findBy({ - userId: me.id, - }); - - return await Promise.all(clips.map((x) => Clips.pack(x))); -}); diff --git a/packages/backend/src/server/api/endpoints/clips/notes.ts b/packages/backend/src/server/api/endpoints/clips/notes.ts deleted file mode 100644 index c641d9ba9f..0000000000 --- a/packages/backend/src/server/api/endpoints/clips/notes.ts +++ /dev/null @@ -1,94 +0,0 @@ -import define from "../../define.js"; -import { ClipNotes, Clips, Notes } from "@/models/index.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { generateVisibilityQuery } from "../../common/generate-visibility-query.js"; -import { generateMutedUserQuery } from "../../common/generate-muted-user-query.js"; -import { ApiError } from "../../error.js"; -import { generateBlockedUserQuery } from "../../common/generate-block-query.js"; - -export const meta = { - tags: ["account", "notes", "clips"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - kind: "read:account", - - errors: { - noSuchClip: { - message: "No such clip.", - code: "NO_SUCH_CLIP", - id: "1d7645e6-2b6d-4635-b0fe-fe22b0e72e00", - }, - }, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - clipId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: ["clipId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const clip = await Clips.findOneBy({ - id: ps.clipId, - }); - - if (clip == null) { - throw new ApiError(meta.errors.noSuchClip); - } - - if (!clip.isPublic && (user == null || clip.userId !== user.id)) { - throw new ApiError(meta.errors.noSuchClip); - } - - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - ps.sinceId, - ps.untilId, - ) - .innerJoin( - ClipNotes.metadata.targetName, - "clipNote", - "clipNote.noteId = note.id", - ) - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner") - .andWhere("clipNote.clipId = :clipId", { clipId: clip.id }); - - if (user) { - generateVisibilityQuery(query, user); - generateMutedUserQuery(query, user); - generateBlockedUserQuery(query, user); - } - - const notes = await query.take(ps.limit).getMany(); - - return await Notes.packMany(notes, user); -}); diff --git a/packages/backend/src/server/api/endpoints/clips/remove-note.ts b/packages/backend/src/server/api/endpoints/clips/remove-note.ts deleted file mode 100644 index 2cc19aca94..0000000000 --- a/packages/backend/src/server/api/endpoints/clips/remove-note.ts +++ /dev/null @@ -1,57 +0,0 @@ -import define from "../../define.js"; -import { ClipNotes, Clips } from "@/models/index.js"; -import { ApiError } from "../../error.js"; -import { getNote } from "../../common/getters.js"; - -export const meta = { - tags: ["account", "notes", "clips"], - - requireCredential: true, - - kind: "write:account", - - errors: { - noSuchClip: { - message: "No such clip.", - code: "NO_SUCH_CLIP", - id: "b80525c6-97f7-49d7-a42d-ebccd49cfd52", - }, - - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "aff017de-190e-434b-893e-33a9ff5049d8", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - clipId: { type: "string", format: "misskey:id" }, - noteId: { type: "string", format: "misskey:id" }, - }, - required: ["clipId", "noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const clip = await Clips.findOneBy({ - id: ps.clipId, - userId: user.id, - }); - - if (clip == null) { - throw new ApiError(meta.errors.noSuchClip); - } - - const note = await getNote(ps.noteId).catch((e) => { - if (e.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw e; - }); - - await ClipNotes.delete({ - noteId: note.id, - clipId: clip.id, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/clips/show.ts b/packages/backend/src/server/api/endpoints/clips/show.ts deleted file mode 100644 index 14709b5040..0000000000 --- a/packages/backend/src/server/api/endpoints/clips/show.ts +++ /dev/null @@ -1,52 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { Clips } from "@/models/index.js"; - -export const meta = { - tags: ["clips", "account"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - kind: "read:account", - - errors: { - noSuchClip: { - message: "No such clip.", - code: "NO_SUCH_CLIP", - id: "c3c5fe33-d62c-44d2-9ea5-d997703f5c20", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "Clip", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - clipId: { type: "string", format: "misskey:id" }, - }, - required: ["clipId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - // Fetch the clip - const clip = await Clips.findOneBy({ - id: ps.clipId, - }); - - if (clip == null) { - throw new ApiError(meta.errors.noSuchClip); - } - - if (!clip.isPublic && (me == null || clip.userId !== me.id)) { - throw new ApiError(meta.errors.noSuchClip); - } - - return await Clips.pack(clip); -}); diff --git a/packages/backend/src/server/api/endpoints/clips/update.ts b/packages/backend/src/server/api/endpoints/clips/update.ts deleted file mode 100644 index e78f36e455..0000000000 --- a/packages/backend/src/server/api/endpoints/clips/update.ts +++ /dev/null @@ -1,62 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { Clips } from "@/models/index.js"; - -export const meta = { - tags: ["clips"], - - requireCredential: true, - - kind: "write:account", - - errors: { - noSuchClip: { - message: "No such clip.", - code: "NO_SUCH_CLIP", - id: "b4d92d70-b216-46fa-9a3f-a8c811699257", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "Clip", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - clipId: { type: "string", format: "misskey:id" }, - name: { type: "string", minLength: 1, maxLength: 100 }, - isPublic: { type: "boolean" }, - description: { - type: "string", - nullable: true, - minLength: 1, - maxLength: 2048, - }, - }, - required: ["clipId", "name"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Fetch the clip - const clip = await Clips.findOneBy({ - id: ps.clipId, - userId: user.id, - }); - - if (clip == null) { - throw new ApiError(meta.errors.noSuchClip); - } - - await Clips.update(clip.id, { - name: ps.name, - description: ps.description, - isPublic: ps.isPublic, - }); - - return await Clips.pack(clip.id); -}); diff --git a/packages/backend/src/server/api/endpoints/compatibility/custom-emojis.ts b/packages/backend/src/server/api/endpoints/compatibility/custom-emojis.ts deleted file mode 100644 index 62e0836e85..0000000000 --- a/packages/backend/src/server/api/endpoints/compatibility/custom-emojis.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { Emojis } from "@/models/index.js"; -import type { Emoji } from "@/models/entities/emoji.js"; -import { IsNull, In } from "typeorm"; -import { FILE_TYPE_BROWSERSAFE } from "@/const.js"; -import define from "../../define.js"; - -export const meta = { - requireCredential: false, - requireCredentialPrivateMode: true, - allowGet: true, - - tags: ["meta"], -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - const now = Date.now(); - const emojis: Emoji[] = await Emojis.find({ - where: { host: IsNull(), type: In(FILE_TYPE_BROWSERSAFE) }, - select: ["name", "originalUrl", "publicUrl", "category"], - }); - - const emojiList = emojis.map((emoji) => ({ - shortcode: emoji.name, - url: emoji.originalUrl, - static_url: emoji.publicUrl, - visible_in_picker: true, - category: emoji.category, - })); - - return emojiList; -}); diff --git a/packages/backend/src/server/api/endpoints/compatibility/instance-info.ts b/packages/backend/src/server/api/endpoints/compatibility/instance-info.ts deleted file mode 100644 index 4e692568c5..0000000000 --- a/packages/backend/src/server/api/endpoints/compatibility/instance-info.ts +++ /dev/null @@ -1,232 +0,0 @@ -import * as mfm from "mfm-js"; -import { toHtml } from "@/mfm/to-html.js"; -import config from "@/config/index.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { - Users, - Notes, - Instances, - UserProfiles, - Emojis, - DriveFiles, -} from "@/models/index.js"; -import type { Emoji } from "@/models/entities/emoji.js"; -import type { User } from "@/models/entities/user.js"; -import { IsNull, In } from "typeorm"; -import { MAX_NOTE_TEXT_LENGTH, FILE_TYPE_BROWSERSAFE } from "@/const.js"; -import define from "../../define.js"; - -export const meta = { - requireCredential: false, - requireCredentialPrivateMode: true, - allowGet: true, - - tags: ["meta"], -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - const now = Date.now(); - const [meta, total, localPosts, instanceCount, firstAdmin, emojis] = - await Promise.all([ - fetchMeta(true), - Users.count({ where: { host: IsNull() } }), - Notes.count({ where: { userHost: IsNull(), replyId: IsNull() } }), - Instances.count(), - Users.findOne({ - where: { - host: IsNull(), - isAdmin: true, - isDeleted: false, - isBot: false, - }, - order: { id: "ASC" }, - }), - Emojis.find({ - where: { host: IsNull(), type: In(FILE_TYPE_BROWSERSAFE) }, - select: ["id", "name", "originalUrl", "publicUrl"], - }).then((l) => - l.reduce((a, e) => { - a[e.name] = e; - return a; - }, {} as Record<string, Emoji>), - ), - ]); - - const descSplit = splitN(meta.description, "\n", 2); - const shortDesc = markup(descSplit.length > 0 ? descSplit[0] : ""); - const longDesc = markup(meta.description ?? ""); - - return { - uri: config.hostname, - title: meta.name, - short_description: shortDesc, - description: longDesc, - email: meta.maintainerEmail, - version: config.version, - urls: { - streaming_api: `wss://${config.host}`, - }, - stats: { - user_count: total, - status_count: localPosts, - domain_count: instanceCount, - }, - thumbnail: meta.logoImageUrl, - languages: meta.langs, - registrations: !meta.disableRegistration, - approval_required: false, - invites_enabled: false, - configuration: { - accounts: { - max_featured_tags: 16, - }, - statuses: { - max_characters: MAX_NOTE_TEXT_LENGTH, - max_media_attachments: 16, - characters_reserved_per_url: 0, - }, - media_attachments: { - supported_mime_types: FILE_TYPE_BROWSERSAFE, - image_size_limit: 10485760, - image_matrix_limit: 16777216, - video_size_limit: 41943040, - video_frame_rate_limit: 60, - video_matrix_limit: 2304000, - }, - polls: { - max_options: 10, - max_characters_per_option: 50, - min_expiration: 15, - max_expiration: -1, - }, - }, - contact_account: await getContact(firstAdmin, emojis), - rules: [], - }; -}); - -const splitN = (s: string | null, split: string, n: number): string[] => { - const ret: string[] = []; - if (s == null) return ret; - if (s === "") { - ret.push(s); - return ret; - } - - let start = 0; - let pos = s.indexOf(split); - if (pos === -1) { - ret.push(s); - return ret; - } - - for (let i = 0; i < n - 1; i++) { - ret.push(s.substring(start, pos)); - start = pos + split.length; - pos = s.indexOf(split, start); - if (pos === -1) break; - } - ret.push(s.substring(start)); - - return ret; -}; - -type ContactType = { - id: string; - username: string; - acct: string; - display_name: string; - note?: string; - noindex?: boolean; - fields?: { - name: string; - value: string; - verified_at: string | null; - }[]; - locked: boolean; - bot: boolean; - created_at: string; - url: string; - followers_count: number; - following_count: number; - statuses_count: number; - last_status_at?: string; - emojis: any; -} | null; - -const getContact = async ( - user: User | null, - emojis: Record<string, Emoji>, -): Promise<ContactType> => { - if (!user) return null; - - let contact: ContactType = { - id: user.id, - username: user.username, - acct: user.username, - display_name: user.name ?? user.username, - locked: user.isLocked, - bot: user.isBot, - created_at: user.createdAt.toISOString(), - url: `${config.url}/@${user.username}`, - followers_count: user.followersCount, - following_count: user.followingCount, - statuses_count: user.notesCount, - last_status_at: user.lastActiveDate?.toISOString(), - emojis: emojis - ? user.emojis - .filter((e, i, a) => e in emojis && a.indexOf(e) === i) - .map((e) => ({ - shortcode: e, - static_url: emojis[e].publicUrl, - url: emojis[e].originalUrl, - visible_in_picker: true, - })) - : [], - }; - - const [profile] = await Promise.all([ - UserProfiles.findOne({ where: { userId: user.id } }), - loadDriveFiles(contact, "avatar", user.avatarId), - loadDriveFiles(contact, "header", user.bannerId), - ]); - - if (!profile) { - return contact; - } - - contact = { - ...contact, - note: markup(profile.description ?? ""), - noindex: profile.noCrawle, - fields: profile.fields.map((f) => ({ - name: f.name, - value: f.value, - verified_at: null, - })), - }; - - return contact; -}; - -const loadDriveFiles = async ( - contact: any, - key: string, - fileId: string | null, -) => { - if (fileId) { - const file = await DriveFiles.findOneBy({ id: fileId }); - if (file) { - contact[key] = file.webpublicUrl ?? file.url; - contact[`${key}_static`] = contact[key]; - } - } -}; - -const markup = (text: string): string => toHtml(mfm.parse(text)) ?? ""; diff --git a/packages/backend/src/server/api/endpoints/custom-motd.ts b/packages/backend/src/server/api/endpoints/custom-motd.ts deleted file mode 100644 index 098a676a57..0000000000 --- a/packages/backend/src/server/api/endpoints/custom-motd.ts +++ /dev/null @@ -1,33 +0,0 @@ -// import { IsNull } from 'typeorm'; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import define from "../define.js"; - -export const meta = { - tags: ["meta"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - const meta = await fetchMeta(); - const motd = await Promise.all(meta.customMOTD.map((x) => x)); - return motd; -}); diff --git a/packages/backend/src/server/api/endpoints/custom-splash-icons.ts b/packages/backend/src/server/api/endpoints/custom-splash-icons.ts deleted file mode 100644 index c4833a4eef..0000000000 --- a/packages/backend/src/server/api/endpoints/custom-splash-icons.ts +++ /dev/null @@ -1,33 +0,0 @@ -// import { IsNull } from 'typeorm'; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import define from "../define.js"; - -export const meta = { - tags: ["meta"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - const meta = await fetchMeta(); - const icons = await Promise.all(meta.customSplashIcons.map((x) => x)); - return icons; -}); diff --git a/packages/backend/src/server/api/endpoints/drive.ts b/packages/backend/src/server/api/endpoints/drive.ts deleted file mode 100644 index ce98b53a6b..0000000000 --- a/packages/backend/src/server/api/endpoints/drive.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { DriveFiles } from "@/models/index.js"; -import define from "../define.js"; - -export const meta = { - tags: ["drive", "account"], - - requireCredential: true, - - kind: "read:drive", - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - capacity: { - type: "number", - optional: false, - nullable: false, - }, - usage: { - type: "number", - optional: false, - nullable: false, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const instance = await fetchMeta(true); - - // Calculate drive usage - const usage = await DriveFiles.calcDriveUsageOf(user.id); - - return { - capacity: - 1024 * - 1024 * - (user.driveCapacityOverrideMb || instance.localDriveCapacityMb), - usage: usage, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/drive/files.ts b/packages/backend/src/server/api/endpoints/drive/files.ts deleted file mode 100644 index c749e49038..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/files.ts +++ /dev/null @@ -1,72 +0,0 @@ -import define from "../../define.js"; -import { DriveFiles } from "@/models/index.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["drive"], - - requireCredential: true, - - kind: "read:drive", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "DriveFile", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - folderId: { - type: "string", - format: "misskey:id", - nullable: true, - default: null, - }, - type: { - type: "string", - nullable: true, - pattern: /^[a-zA-Z\/\-*]+$/.toString().slice(1, -1), - }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = makePaginationQuery( - DriveFiles.createQueryBuilder("file"), - ps.sinceId, - ps.untilId, - ).andWhere("file.userId = :userId", { userId: user.id }); - - if (ps.folderId) { - query.andWhere("file.folderId = :folderId", { folderId: ps.folderId }); - } else { - query.andWhere("file.folderId IS NULL"); - } - - if (ps.type) { - if (ps.type.endsWith("/*")) { - query.andWhere("file.type like :type", { - type: `${ps.type.replace("/*", "/")}%`, - }); - } else { - query.andWhere("file.type = :type", { type: ps.type }); - } - } - - const files = await query.take(ps.limit).getMany(); - - return await DriveFiles.packMany(files, { detail: false, self: true }); -}); diff --git a/packages/backend/src/server/api/endpoints/drive/files/attached-notes.ts b/packages/backend/src/server/api/endpoints/drive/files/attached-notes.ts deleted file mode 100644 index 9267da5856..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/files/attached-notes.ts +++ /dev/null @@ -1,61 +0,0 @@ -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { DriveFiles, Notes } from "@/models/index.js"; - -export const meta = { - tags: ["drive", "notes"], - - requireCredential: true, - - kind: "read:drive", - - description: "Find the notes to which the given file is attached.", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, - - errors: { - noSuchFile: { - message: "No such file.", - code: "NO_SUCH_FILE", - id: "c118ece3-2e4b-4296-99d1-51756e32d232", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - fileId: { type: "string", format: "misskey:id" }, - }, - required: ["fileId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Fetch file - const file = await DriveFiles.findOneBy({ - id: ps.fileId, - userId: user.id, - }); - - if (file == null) { - throw new ApiError(meta.errors.noSuchFile); - } - - const notes = await Notes.createQueryBuilder("note") - .where(":file = ANY(note.fileIds)", { file: file.id }) - .getMany(); - - return await Notes.packMany(notes, user, { - detail: true, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/drive/files/caption-image.ts b/packages/backend/src/server/api/endpoints/drive/files/caption-image.ts deleted file mode 100644 index 1ab817bd0c..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/files/caption-image.ts +++ /dev/null @@ -1,42 +0,0 @@ -import define from "../../../define.js"; -import { createWorker } from "tesseract.js"; - -export const meta = { - tags: ["drive"], - - requireCredential: true, - - kind: "read:drive", - - description: "Return caption of image", - - res: { - type: "string", - optional: false, - nullable: false, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - url: { type: "string" }, - }, - required: ["url"], -} as const; - -export default define(meta, paramDef, async (ps) => { - const worker = createWorker({ - logger: (m) => console.log(m), - }); - - await worker.load(); - await worker.loadLanguage("eng"); - await worker.initialize("eng"); - const { - data: { text }, - } = await worker.recognize(ps.url); - await worker.terminate(); - - return text; -}); diff --git a/packages/backend/src/server/api/endpoints/drive/files/check-existence.ts b/packages/backend/src/server/api/endpoints/drive/files/check-existence.ts deleted file mode 100644 index df89685201..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/files/check-existence.ts +++ /dev/null @@ -1,35 +0,0 @@ -import define from "../../../define.js"; -import { DriveFiles } from "@/models/index.js"; - -export const meta = { - tags: ["drive"], - - requireCredential: true, - - kind: "read:drive", - - description: "Check if a given file exists.", - - res: { - type: "boolean", - optional: false, - nullable: false, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - md5: { type: "string" }, - }, - required: ["md5"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const file = await DriveFiles.findOneBy({ - md5: ps.md5, - userId: user.id, - }); - - return file != null; -}); diff --git a/packages/backend/src/server/api/endpoints/drive/files/create.ts b/packages/backend/src/server/api/endpoints/drive/files/create.ts deleted file mode 100644 index 0a167178b2..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/files/create.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { addFile } from "@/services/drive/add-file.js"; -import { DriveFiles } from "@/models/index.js"; -import { DB_MAX_IMAGE_COMMENT_LENGTH } from "@/misc/hard-limits.js"; -import { IdentifiableError } from "@/misc/identifiable-error.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { HOUR } from "@/const.js"; -import define from "../../../define.js"; -import { apiLogger } from "../../../logger.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["drive"], - - requireCredential: true, - - limit: { - duration: HOUR, - max: 120, - }, - - requireFile: true, - - kind: "write:drive", - - description: "Upload a new drive file.", - - res: { - type: "object", - optional: false, - nullable: false, - ref: "DriveFile", - }, - - errors: { - invalidFileName: { - message: "Invalid file name.", - code: "INVALID_FILE_NAME", - id: "f449b209-0c60-4e51-84d5-29486263bfd4", - }, - - inappropriate: { - message: - "Cannot upload the file because it has been determined that it possibly contains inappropriate content.", - code: "INAPPROPRIATE", - id: "bec5bd69-fba3-43c9-b4fb-2894b66ad5d2", - }, - - noFreeSpace: { - message: - "Cannot upload the file because you have no free space of drive.", - code: "NO_FREE_SPACE", - id: "d08dbc37-a6a9-463a-8c47-96c32ab5f064", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - folderId: { - type: "string", - format: "misskey:id", - nullable: true, - default: null, - }, - name: { type: "string", nullable: true, default: null }, - comment: { - type: "string", - nullable: true, - maxLength: DB_MAX_IMAGE_COMMENT_LENGTH, - default: null, - }, - isSensitive: { type: "boolean", default: false }, - force: { type: "boolean", default: false }, - }, - required: [], -} as const; - -export default define( - meta, - paramDef, - async (ps, user, _, file, cleanup, ip, headers) => { - // Get 'name' parameter - let name = ps.name || file.originalname; - if (name !== undefined && name !== null) { - name = name.trim(); - if (name.length === 0) { - name = null; - } else if (name === "blob") { - name = null; - } else if (!DriveFiles.validateFileName(name)) { - throw new ApiError(meta.errors.invalidFileName); - } - } else { - name = null; - } - - const meta = await fetchMeta(); - - try { - // Create file - const driveFile = await addFile({ - user, - path: file.path, - name, - comment: ps.comment, - folderId: ps.folderId, - force: ps.force, - sensitive: ps.isSensitive, - requestIp: meta.enableIpLogging ? ip : null, - requestHeaders: meta.enableIpLogging ? headers : null, - }); - return await DriveFiles.pack(driveFile, { self: true }); - } catch (e) { - if (e instanceof Error || typeof e === "string") { - apiLogger.error(e); - } - if (e instanceof IdentifiableError) { - if (e.id === "282f77bf-5816-4f72-9264-aa14d8261a21") - throw new ApiError(meta.errors.inappropriate); - if (e.id === "c6244ed2-a39a-4e1c-bf93-f0fbd7764fa6") - throw new ApiError(meta.errors.noFreeSpace); - } - throw new ApiError(); - } finally { - cleanup!(); - } - }, -); diff --git a/packages/backend/src/server/api/endpoints/drive/files/delete.ts b/packages/backend/src/server/api/endpoints/drive/files/delete.ts deleted file mode 100644 index 4e8b4156f3..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/files/delete.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { deleteFile } from "@/services/drive/delete-file.js"; -import { publishDriveStream } from "@/services/stream.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { DriveFiles, Users } from "@/models/index.js"; - -export const meta = { - tags: ["drive"], - - requireCredential: true, - - kind: "write:drive", - - description: "Delete an existing drive file.", - - errors: { - noSuchFile: { - message: "No such file.", - code: "NO_SUCH_FILE", - id: "908939ec-e52b-4458-b395-1025195cea58", - }, - - accessDenied: { - message: "Access denied.", - code: "ACCESS_DENIED", - id: "5eb8d909-2540-4970-90b8-dd6f86088121", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - fileId: { type: "string", format: "misskey:id" }, - }, - required: ["fileId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const file = await DriveFiles.findOneBy({ id: ps.fileId }); - - if (file == null) { - throw new ApiError(meta.errors.noSuchFile); - } - - if (!(user.isAdmin || user.isModerator) && file.userId !== user.id) { - throw new ApiError(meta.errors.accessDenied); - } - - // Delete - await deleteFile(file); - - // Publish fileDeleted event - publishDriveStream(user.id, "fileDeleted", file.id); -}); diff --git a/packages/backend/src/server/api/endpoints/drive/files/find-by-hash.ts b/packages/backend/src/server/api/endpoints/drive/files/find-by-hash.ts deleted file mode 100644 index ce14f4e09e..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/files/find-by-hash.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { DriveFiles } from "@/models/index.js"; -import define from "../../../define.js"; - -export const meta = { - tags: ["drive"], - - requireCredential: true, - - kind: "read:drive", - - description: "Search for a drive file by a hash of the contents.", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "DriveFile", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - md5: { type: "string" }, - }, - required: ["md5"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const files = await DriveFiles.findBy({ - md5: ps.md5, - userId: user.id, - }); - - return await DriveFiles.packMany(files, { self: true }); -}); diff --git a/packages/backend/src/server/api/endpoints/drive/files/find.ts b/packages/backend/src/server/api/endpoints/drive/files/find.ts deleted file mode 100644 index c2ad95126f..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/files/find.ts +++ /dev/null @@ -1,51 +0,0 @@ -import define from "../../../define.js"; -import { DriveFiles } from "@/models/index.js"; -import { IsNull } from "typeorm"; - -export const meta = { - requireCredential: true, - - tags: ["drive"], - - kind: "read:drive", - - description: "Search for a drive file by the given parameters.", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "DriveFile", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - name: { type: "string" }, - folderId: { - type: "string", - format: "misskey:id", - nullable: true, - default: null, - }, - }, - required: ["name"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const files = await DriveFiles.findBy({ - name: ps.name, - userId: user.id, - folderId: ps.folderId ?? IsNull(), - }); - - return await Promise.all( - files.map((file) => DriveFiles.pack(file, { self: true })), - ); -}); diff --git a/packages/backend/src/server/api/endpoints/drive/files/show.ts b/packages/backend/src/server/api/endpoints/drive/files/show.ts deleted file mode 100644 index 291e3f56bb..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/files/show.ts +++ /dev/null @@ -1,89 +0,0 @@ -import type { DriveFile } from "@/models/entities/drive-file.js"; -import { DriveFiles, Users } from "@/models/index.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["drive"], - - requireCredential: true, - - kind: "read:drive", - - description: "Show the properties of a drive file.", - - res: { - type: "object", - optional: false, - nullable: false, - ref: "DriveFile", - }, - - errors: { - noSuchFile: { - message: "No such file.", - code: "NO_SUCH_FILE", - id: "067bc436-2718-4795-b0fb-ecbe43949e31", - }, - - accessDenied: { - message: "Access denied.", - code: "ACCESS_DENIED", - id: "25b73c73-68b1-41d0-bad1-381cfdf6579f", - }, - }, -} as const; - -export const paramDef = { - type: "object", - anyOf: [ - { - properties: { - fileId: { type: "string", format: "misskey:id" }, - }, - required: ["fileId"], - }, - { - properties: { - url: { type: "string" }, - }, - required: ["url"], - }, - ], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - let file: DriveFile | null = null; - - if (ps.fileId) { - file = await DriveFiles.findOneBy({ id: ps.fileId }); - } else if (ps.url) { - file = await DriveFiles.findOne({ - where: [ - { - url: ps.url, - }, - { - webpublicUrl: ps.url, - }, - { - thumbnailUrl: ps.url, - }, - ], - }); - } - - if (file == null) { - throw new ApiError(meta.errors.noSuchFile); - } - - if (!(user.isAdmin || user.isModerator) && file.userId !== user.id) { - throw new ApiError(meta.errors.accessDenied); - } - - return await DriveFiles.pack(file, { - detail: true, - withUser: true, - self: true, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/drive/files/update.ts b/packages/backend/src/server/api/endpoints/drive/files/update.ts deleted file mode 100644 index e833fddb58..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/files/update.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { publishDriveStream } from "@/services/stream.js"; -import { DriveFiles, DriveFolders, Users } from "@/models/index.js"; -import { DB_MAX_IMAGE_COMMENT_LENGTH } from "@/misc/hard-limits.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["drive"], - - requireCredential: true, - - kind: "write:drive", - - description: "Update the properties of a drive file.", - - errors: { - invalidFileName: { - message: "Invalid file name.", - code: "INVALID_FILE_NAME", - id: "395e7156-f9f0-475e-af89-53c3c23080c2", - }, - - noSuchFile: { - message: "No such file.", - code: "NO_SUCH_FILE", - id: "e7778c7e-3af9-49cd-9690-6dbc3e6c972d", - }, - - accessDenied: { - message: "Access denied.", - code: "ACCESS_DENIED", - id: "01a53b27-82fc-445b-a0c1-b558465a8ed2", - }, - - noSuchFolder: { - message: "No such folder.", - code: "NO_SUCH_FOLDER", - id: "ea8fb7a5-af77-4a08-b608-c0218176cd73", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "DriveFile", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - fileId: { type: "string", format: "misskey:id" }, - folderId: { type: "string", format: "misskey:id", nullable: true }, - name: { type: "string" }, - isSensitive: { type: "boolean" }, - comment: { - type: "string", - nullable: true, - maxLength: DB_MAX_IMAGE_COMMENT_LENGTH, - }, - }, - required: ["fileId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const file = await DriveFiles.findOneBy({ id: ps.fileId }); - - if (file == null) { - throw new ApiError(meta.errors.noSuchFile); - } - - if (!(user.isAdmin || user.isModerator) && file.userId !== user.id) { - throw new ApiError(meta.errors.accessDenied); - } - - if (ps.name) file.name = ps.name; - if (!DriveFiles.validateFileName(file.name)) { - throw new ApiError(meta.errors.invalidFileName); - } - - if (ps.comment !== undefined) file.comment = ps.comment; - - if (ps.isSensitive !== undefined) file.isSensitive = ps.isSensitive; - - if (ps.folderId !== undefined) { - if (ps.folderId === null) { - file.folderId = null; - } else { - const folder = await DriveFolders.findOneBy({ - id: ps.folderId, - userId: user.id, - }); - - if (folder == null) { - throw new ApiError(meta.errors.noSuchFolder); - } - - file.folderId = folder.id; - } - } - - await DriveFiles.update(file.id, { - name: file.name, - comment: file.comment, - folderId: file.folderId, - isSensitive: file.isSensitive, - }); - - const fileObj = await DriveFiles.pack(file, { self: true }); - - // Publish fileUpdated event - publishDriveStream(user.id, "fileUpdated", fileObj); - - return fileObj; -}); diff --git a/packages/backend/src/server/api/endpoints/drive/files/upload-from-url.ts b/packages/backend/src/server/api/endpoints/drive/files/upload-from-url.ts deleted file mode 100644 index 7bb47dbef5..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/files/upload-from-url.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { uploadFromUrl } from "@/services/drive/upload-from-url.js"; -import define from "../../../define.js"; -import { DriveFiles } from "@/models/index.js"; -import { publishMainStream } from "@/services/stream.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - tags: ["drive"], - - limit: { - duration: HOUR, - max: 60, - }, - - description: - "Request the server to download a new drive file from the specified URL.", - - requireCredential: true, - - kind: "write:drive", -} as const; - -export const paramDef = { - type: "object", - properties: { - url: { type: "string" }, - folderId: { - type: "string", - format: "misskey:id", - nullable: true, - default: null, - }, - isSensitive: { type: "boolean", default: false }, - comment: { type: "string", nullable: true, maxLength: 512, default: null }, - marker: { type: "string", nullable: true, default: null }, - force: { type: "boolean", default: false }, - }, - required: ["url"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - uploadFromUrl({ - url: ps.url, - user, - folderId: ps.folderId, - sensitive: ps.isSensitive, - force: ps.force, - comment: ps.comment, - }).then((file) => { - DriveFiles.pack(file, { self: true }).then((packedFile) => { - publishMainStream(user.id, "urlUploadFinished", { - marker: ps.marker, - file: packedFile, - }); - }); - }); -}); diff --git a/packages/backend/src/server/api/endpoints/drive/folders.ts b/packages/backend/src/server/api/endpoints/drive/folders.ts deleted file mode 100644 index ed0d38844b..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/folders.ts +++ /dev/null @@ -1,57 +0,0 @@ -import define from "../../define.js"; -import { DriveFolders } from "@/models/index.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["drive"], - - requireCredential: true, - - kind: "read:drive", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "DriveFolder", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - folderId: { - type: "string", - format: "misskey:id", - nullable: true, - default: null, - }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = makePaginationQuery( - DriveFolders.createQueryBuilder("folder"), - ps.sinceId, - ps.untilId, - ).andWhere("folder.userId = :userId", { userId: user.id }); - - if (ps.folderId) { - query.andWhere("folder.parentId = :parentId", { parentId: ps.folderId }); - } else { - query.andWhere("folder.parentId IS NULL"); - } - - const folders = await query.take(ps.limit).getMany(); - - return await Promise.all(folders.map((folder) => DriveFolders.pack(folder))); -}); diff --git a/packages/backend/src/server/api/endpoints/drive/folders/create.ts b/packages/backend/src/server/api/endpoints/drive/folders/create.ts deleted file mode 100644 index d50f5f2815..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/folders/create.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { publishDriveStream } from "@/services/stream.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { DriveFolders } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; - -export const meta = { - tags: ["drive"], - - requireCredential: true, - - kind: "write:drive", - - errors: { - noSuchFolder: { - message: "No such folder.", - code: "NO_SUCH_FOLDER", - id: "53326628-a00d-40a6-a3cd-8975105c0f95", - }, - }, - - res: { - type: "object" as const, - optional: false as const, - nullable: false as const, - ref: "DriveFolder", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - name: { type: "string", default: "Untitled", maxLength: 200 }, - parentId: { type: "string", format: "misskey:id", nullable: true }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // If the parent folder is specified - let parent = null; - if (ps.parentId) { - // Fetch parent folder - parent = await DriveFolders.findOneBy({ - id: ps.parentId, - userId: user.id, - }); - - if (parent == null) { - throw new ApiError(meta.errors.noSuchFolder); - } - } - - // Create folder - const folder = await DriveFolders.insert({ - id: genId(), - createdAt: new Date(), - name: ps.name, - parentId: parent !== null ? parent.id : null, - userId: user.id, - }).then((x) => DriveFolders.findOneByOrFail(x.identifiers[0])); - - const folderObj = await DriveFolders.pack(folder); - - // Publish folderCreated event - publishDriveStream(user.id, "folderCreated", folderObj); - - return folderObj; -}); diff --git a/packages/backend/src/server/api/endpoints/drive/folders/delete.ts b/packages/backend/src/server/api/endpoints/drive/folders/delete.ts deleted file mode 100644 index 98895a7320..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/folders/delete.ts +++ /dev/null @@ -1,60 +0,0 @@ -import define from "../../../define.js"; -import { publishDriveStream } from "@/services/stream.js"; -import { ApiError } from "../../../error.js"; -import { DriveFolders, DriveFiles } from "@/models/index.js"; - -export const meta = { - tags: ["drive"], - - requireCredential: true, - - kind: "write:drive", - - errors: { - noSuchFolder: { - message: "No such folder.", - code: "NO_SUCH_FOLDER", - id: "1069098f-c281-440f-b085-f9932edbe091", - }, - - hasChildFilesOrFolders: { - message: "This folder has child files or folders.", - code: "HAS_CHILD_FILES_OR_FOLDERS", - id: "b0fc8a17-963c-405d-bfbc-859a487295e1", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - folderId: { type: "string", format: "misskey:id" }, - }, - required: ["folderId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Get folder - const folder = await DriveFolders.findOneBy({ - id: ps.folderId, - userId: user.id, - }); - - if (folder == null) { - throw new ApiError(meta.errors.noSuchFolder); - } - - const [childFoldersCount, childFilesCount] = await Promise.all([ - DriveFolders.countBy({ parentId: folder.id }), - DriveFiles.countBy({ folderId: folder.id }), - ]); - - if (childFoldersCount !== 0 || childFilesCount !== 0) { - throw new ApiError(meta.errors.hasChildFilesOrFolders); - } - - await DriveFolders.delete(folder.id); - - // Publish folderCreated event - publishDriveStream(user.id, "folderDeleted", folder.id); -}); diff --git a/packages/backend/src/server/api/endpoints/drive/folders/find.ts b/packages/backend/src/server/api/endpoints/drive/folders/find.ts deleted file mode 100644 index 45451fb90b..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/folders/find.ts +++ /dev/null @@ -1,47 +0,0 @@ -import define from "../../../define.js"; -import { DriveFolders } from "@/models/index.js"; -import { IsNull } from "typeorm"; - -export const meta = { - tags: ["drive"], - - requireCredential: true, - - kind: "read:drive", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "DriveFolder", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - name: { type: "string" }, - parentId: { - type: "string", - format: "misskey:id", - nullable: true, - default: null, - }, - }, - required: ["name"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const folders = await DriveFolders.findBy({ - name: ps.name, - userId: user.id, - parentId: ps.parentId ?? IsNull(), - }); - - return await Promise.all(folders.map((folder) => DriveFolders.pack(folder))); -}); diff --git a/packages/backend/src/server/api/endpoints/drive/folders/show.ts b/packages/backend/src/server/api/endpoints/drive/folders/show.ts deleted file mode 100644 index 6a72a22777..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/folders/show.ts +++ /dev/null @@ -1,50 +0,0 @@ -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { DriveFolders } from "@/models/index.js"; - -export const meta = { - tags: ["drive"], - - requireCredential: true, - - kind: "read:drive", - - res: { - type: "object", - optional: false, - nullable: false, - ref: "DriveFolder", - }, - - errors: { - noSuchFolder: { - message: "No such folder.", - code: "NO_SUCH_FOLDER", - id: "d74ab9eb-bb09-4bba-bf24-fb58f761e1e9", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - folderId: { type: "string", format: "misskey:id" }, - }, - required: ["folderId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Get folder - const folder = await DriveFolders.findOneBy({ - id: ps.folderId, - userId: user.id, - }); - - if (folder == null) { - throw new ApiError(meta.errors.noSuchFolder); - } - - return await DriveFolders.pack(folder, { - detail: true, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/drive/folders/update.ts b/packages/backend/src/server/api/endpoints/drive/folders/update.ts deleted file mode 100644 index 929a69bdec..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/folders/update.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { publishDriveStream } from "@/services/stream.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { DriveFolders } from "@/models/index.js"; - -export const meta = { - tags: ["drive"], - - requireCredential: true, - - kind: "write:drive", - - errors: { - noSuchFolder: { - message: "No such folder.", - code: "NO_SUCH_FOLDER", - id: "f7974dac-2c0d-4a27-926e-23583b28e98e", - }, - - noSuchParentFolder: { - message: "No such parent folder.", - code: "NO_SUCH_PARENT_FOLDER", - id: "ce104e3a-faaf-49d5-b459-10ff0cbbcaa1", - }, - - recursiveNesting: { - message: "It can not be structured like nesting folders recursively.", - code: "NO_SUCH_PARENT_FOLDER", - id: "ce104e3a-faaf-49d5-b459-10ff0cbbcaa1", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "DriveFolder", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - folderId: { type: "string", format: "misskey:id" }, - name: { type: "string", maxLength: 200 }, - parentId: { type: "string", format: "misskey:id", nullable: true }, - }, - required: ["folderId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Fetch folder - const folder = await DriveFolders.findOneBy({ - id: ps.folderId, - userId: user.id, - }); - - if (folder == null) { - throw new ApiError(meta.errors.noSuchFolder); - } - - if (ps.name) folder.name = ps.name; - - if (ps.parentId !== undefined) { - if (ps.parentId === folder.id) { - throw new ApiError(meta.errors.recursiveNesting); - } else if (ps.parentId === null) { - folder.parentId = null; - } else { - // Get parent folder - const parent = await DriveFolders.findOneBy({ - id: ps.parentId, - userId: user.id, - }); - - if (parent == null) { - throw new ApiError(meta.errors.noSuchParentFolder); - } - - // Check if the circular reference will occur - async function checkCircle(folderId: string): Promise<boolean> { - // Fetch folder - const folder2 = await DriveFolders.findOneBy({ - id: folderId, - }); - - if (folder2!.id === folder!.id) { - return true; - } else if (folder2!.parentId) { - return await checkCircle(folder2!.parentId); - } else { - return false; - } - } - - if (parent.parentId !== null) { - if (await checkCircle(parent.parentId)) { - throw new ApiError(meta.errors.recursiveNesting); - } - } - - folder.parentId = parent.id; - } - } - - // Update - DriveFolders.update(folder.id, { - name: folder.name, - parentId: folder.parentId, - }); - - const folderObj = await DriveFolders.pack(folder); - - // Publish folderUpdated event - publishDriveStream(user.id, "folderUpdated", folderObj); - - return folderObj; -}); diff --git a/packages/backend/src/server/api/endpoints/drive/stream.ts b/packages/backend/src/server/api/endpoints/drive/stream.ts deleted file mode 100644 index 0c9654ca23..0000000000 --- a/packages/backend/src/server/api/endpoints/drive/stream.ts +++ /dev/null @@ -1,59 +0,0 @@ -import define from "../../define.js"; -import { DriveFiles } from "@/models/index.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["drive"], - - requireCredential: true, - - kind: "read:drive", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "DriveFile", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - type: { - type: "string", - pattern: /^[a-zA-Z\/\-*]+$/.toString().slice(1, -1), - }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = makePaginationQuery( - DriveFiles.createQueryBuilder("file"), - ps.sinceId, - ps.untilId, - ).andWhere("file.userId = :userId", { userId: user.id }); - - if (ps.type) { - if (ps.type.endsWith("/*")) { - query.andWhere("file.type like :type", { - type: `${ps.type.replace("/*", "/")}%`, - }); - } else { - query.andWhere("file.type = :type", { type: ps.type }); - } - } - - const files = await query.take(ps.limit).getMany(); - - return await DriveFiles.packMany(files, { detail: false, self: true }); -}); diff --git a/packages/backend/src/server/api/endpoints/email-address/available.ts b/packages/backend/src/server/api/endpoints/email-address/available.ts deleted file mode 100644 index dc3c5e4b8e..0000000000 --- a/packages/backend/src/server/api/endpoints/email-address/available.ts +++ /dev/null @@ -1,38 +0,0 @@ -import define from "../../define.js"; -import { validateEmailForAccount } from "@/services/validate-email-for-account.js"; - -export const meta = { - tags: ["users"], - - requireCredential: false, - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - available: { - type: "boolean", - optional: false, - nullable: false, - }, - reason: { - type: "string", - optional: false, - nullable: true, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - emailAddress: { type: "string" }, - }, - required: ["emailAddress"], -} as const; - -export default define(meta, paramDef, async (ps) => { - return await validateEmailForAccount(ps.emailAddress); -}); diff --git a/packages/backend/src/server/api/endpoints/emoji.ts b/packages/backend/src/server/api/endpoints/emoji.ts deleted file mode 100644 index ddfad77374..0000000000 --- a/packages/backend/src/server/api/endpoints/emoji.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { IsNull } from "typeorm"; -import { Emojis } from "@/models/index.js"; -import define from "../define.js"; - -export const meta = { - tags: ["meta"], - - requireCredential: false, - allowGet: true, - cacheSec: 3600, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "Emoji", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - name: { - type: "string", - }, - }, - required: ["name"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const emoji = await Emojis.findOneOrFail({ - where: { - name: ps.name, - host: IsNull(), - }, - }); - - return Emojis.pack(emoji); -}); diff --git a/packages/backend/src/server/api/endpoints/endpoint.ts b/packages/backend/src/server/api/endpoints/endpoint.ts deleted file mode 100644 index ad0ce45623..0000000000 --- a/packages/backend/src/server/api/endpoints/endpoint.ts +++ /dev/null @@ -1,27 +0,0 @@ -import define from "../define.js"; -import endpoints from "../endpoints.js"; - -export const meta = { - requireCredential: false, - - tags: ["meta"], -} as const; - -export const paramDef = { - type: "object", - properties: { - endpoint: { type: "string" }, - }, - required: ["endpoint"], -} as const; - -export default define(meta, paramDef, async (ps) => { - const ep = endpoints.find((x) => x.name === ps.endpoint); - if (ep == null) return null; - return { - params: Object.entries(ep.params.properties || {}).map(([k, v]) => ({ - name: k, - type: v.type.charAt(0).toUpperCase() + v.type.slice(1), - })), - }; -}); diff --git a/packages/backend/src/server/api/endpoints/endpoints.ts b/packages/backend/src/server/api/endpoints/endpoints.ts deleted file mode 100644 index c5844f8437..0000000000 --- a/packages/backend/src/server/api/endpoints/endpoints.ts +++ /dev/null @@ -1,35 +0,0 @@ -import define from "../define.js"; -import endpoints from "../endpoints.js"; - -export const meta = { - requireCredential: false, - - tags: ["meta"], - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - example: [ - "admin/abuse-user-reports", - "admin/accounts/create", - "admin/announcements/create", - "...", - ], - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - return endpoints.map((x) => x.name); -}); diff --git a/packages/backend/src/server/api/endpoints/export-custom-emojis.ts b/packages/backend/src/server/api/endpoints/export-custom-emojis.ts deleted file mode 100644 index f4fc43c173..0000000000 --- a/packages/backend/src/server/api/endpoints/export-custom-emojis.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { createExportCustomEmojisJob } from "@/queue/index.js"; -import define from "../define.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - secure: true, - requireCredential: true, - limit: { - duration: HOUR, - max: 1, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - createExportCustomEmojisJob(user); -}); diff --git a/packages/backend/src/server/api/endpoints/federation/followers.ts b/packages/backend/src/server/api/endpoints/federation/followers.ts deleted file mode 100644 index 4c6d83abdb..0000000000 --- a/packages/backend/src/server/api/endpoints/federation/followers.ts +++ /dev/null @@ -1,46 +0,0 @@ -import define from "../../define.js"; -import { Followings } from "@/models/index.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["federation"], - - requireCredential: true, - requireAdmin: true, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Following", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - host: { type: "string" }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - }, - required: ["host"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = makePaginationQuery( - Followings.createQueryBuilder("following"), - ps.sinceId, - ps.untilId, - ).andWhere("following.followeeHost = :host", { host: ps.host }); - - const followings = await query.take(ps.limit).getMany(); - - return await Followings.packMany(followings, me, { populateFollowee: true }); -}); diff --git a/packages/backend/src/server/api/endpoints/federation/following.ts b/packages/backend/src/server/api/endpoints/federation/following.ts deleted file mode 100644 index 88b168600b..0000000000 --- a/packages/backend/src/server/api/endpoints/federation/following.ts +++ /dev/null @@ -1,46 +0,0 @@ -import define from "../../define.js"; -import { Followings } from "@/models/index.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["federation"], - - requireCredential: true, - requireAdmin: true, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Following", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - host: { type: "string" }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - }, - required: ["host"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = makePaginationQuery( - Followings.createQueryBuilder("following"), - ps.sinceId, - ps.untilId, - ).andWhere("following.followerHost = :host", { host: ps.host }); - - const followings = await query.take(ps.limit).getMany(); - - return await Followings.packMany(followings, me, { populateFollowee: true }); -}); diff --git a/packages/backend/src/server/api/endpoints/federation/instances.ts b/packages/backend/src/server/api/endpoints/federation/instances.ts deleted file mode 100644 index 8f6184b196..0000000000 --- a/packages/backend/src/server/api/endpoints/federation/instances.ts +++ /dev/null @@ -1,171 +0,0 @@ -import config from "@/config/index.js"; -import define from "../../define.js"; -import { Instances } from "@/models/index.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; - -export const meta = { - tags: ["federation"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "FederationInstance", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - host: { - type: "string", - nullable: true, - description: "Omit or use `null` to not filter by host.", - }, - blocked: { type: "boolean", nullable: true }, - notResponding: { type: "boolean", nullable: true }, - suspended: { type: "boolean", nullable: true }, - federating: { type: "boolean", nullable: true }, - subscribing: { type: "boolean", nullable: true }, - publishing: { type: "boolean", nullable: true }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 30 }, - offset: { type: "integer", default: 0 }, - sort: { type: "string" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = Instances.createQueryBuilder("instance"); - - switch (ps.sort) { - case "+pubSub": - query - .orderBy("instance.followingCount", "DESC") - .orderBy("instance.followersCount", "DESC"); - break; - case "-pubSub": - query - .orderBy("instance.followingCount", "ASC") - .orderBy("instance.followersCount", "ASC"); - break; - case "+notes": - query.orderBy("instance.notesCount", "DESC"); - break; - case "-notes": - query.orderBy("instance.notesCount", "ASC"); - break; - case "+users": - query.orderBy("instance.usersCount", "DESC"); - break; - case "-users": - query.orderBy("instance.usersCount", "ASC"); - break; - case "+following": - query.orderBy("instance.followingCount", "DESC"); - break; - case "-following": - query.orderBy("instance.followingCount", "ASC"); - break; - case "+followers": - query.orderBy("instance.followersCount", "DESC"); - break; - case "-followers": - query.orderBy("instance.followersCount", "ASC"); - break; - case "+caughtAt": - query.orderBy("instance.caughtAt", "DESC"); - break; - case "-caughtAt": - query.orderBy("instance.caughtAt", "ASC"); - break; - case "+lastCommunicatedAt": - query.orderBy("instance.lastCommunicatedAt", "DESC"); - break; - case "-lastCommunicatedAt": - query.orderBy("instance.lastCommunicatedAt", "ASC"); - break; - - default: - query.orderBy("instance.id", "DESC"); - break; - } - - if (typeof ps.blocked === "boolean") { - const meta = await fetchMeta(true); - if (ps.blocked) { - if (meta.blockedHosts.length === 0) { - return []; - } - query.andWhere("instance.host IN (:...blocks)", { - blocks: meta.blockedHosts, - }); - } else if (meta.blockedHosts.length > 0) { - query.andWhere("instance.host NOT IN (:...blocks)", { - blocks: meta.blockedHosts, - }); - } - } - - if (typeof ps.notResponding === "boolean") { - if (ps.notResponding) { - query.andWhere("instance.isNotResponding = TRUE"); - } else { - query.andWhere("instance.isNotResponding = FALSE"); - } - } - - if (typeof ps.suspended === "boolean") { - if (ps.suspended) { - query.andWhere("instance.isSuspended = TRUE"); - } else { - query.andWhere("instance.isSuspended = FALSE"); - } - } - - if (typeof ps.federating === "boolean") { - if (ps.federating) { - query.andWhere( - "((instance.followingCount > 0) OR (instance.followersCount > 0))", - ); - } else { - query.andWhere( - "((instance.followingCount = 0) AND (instance.followersCount = 0))", - ); - } - } - - if (typeof ps.subscribing === "boolean") { - if (ps.subscribing) { - query.andWhere("instance.followersCount > 0"); - } else { - query.andWhere("instance.followersCount = 0"); - } - } - - if (typeof ps.publishing === "boolean") { - if (ps.publishing) { - query.andWhere("instance.followingCount > 0"); - } else { - query.andWhere("instance.followingCount = 0"); - } - } - - if (ps.host) { - query.andWhere("instance.host like :host", { - host: `%${ps.host.toLowerCase()}%`, - }); - } - - const instances = await query.take(ps.limit).skip(ps.offset).getMany(); - - return await Instances.packMany(instances); -}); diff --git a/packages/backend/src/server/api/endpoints/federation/show-instance.ts b/packages/backend/src/server/api/endpoints/federation/show-instance.ts deleted file mode 100644 index 633bb57073..0000000000 --- a/packages/backend/src/server/api/endpoints/federation/show-instance.ts +++ /dev/null @@ -1,36 +0,0 @@ -import define from "../../define.js"; -import { Instances } from "@/models/index.js"; -import { toPuny } from "@/misc/convert-host.js"; - -export const meta = { - tags: ["federation"], - - requireCredential: true, - requireCredentialPrivateMode: true, - - res: { - oneOf: [ - { - type: "object", - ref: "FederationInstance", - }, - { - type: "null", - }, - ], - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - host: { type: "string" }, - }, - required: ["host"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const instance = await Instances.findOneBy({ host: toPuny(ps.host) }); - - return instance ? await Instances.pack(instance) : null; -}); diff --git a/packages/backend/src/server/api/endpoints/federation/stats.ts b/packages/backend/src/server/api/endpoints/federation/stats.ts deleted file mode 100644 index ede7a56c27..0000000000 --- a/packages/backend/src/server/api/endpoints/federation/stats.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { IsNull, MoreThan, Not } from "typeorm"; -import { Followings, Instances } from "@/models/index.js"; -import { awaitAll } from "@/prelude/await-all.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["federation"], - - requireCredential: false, - - allowGet: true, - cacheSec: 60 * 60, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps) => { - const [topSubInstances, topPubInstances, allSubCount, allPubCount] = - await Promise.all([ - Instances.find({ - where: { - followersCount: MoreThan(0), - }, - order: { - followersCount: "DESC", - }, - take: ps.limit, - }), - Instances.find({ - where: { - followingCount: MoreThan(0), - }, - order: { - followingCount: "DESC", - }, - take: ps.limit, - }), - Followings.count({ - where: { - followeeHost: Not(IsNull()), - }, - }), - Followings.count({ - where: { - followerHost: Not(IsNull()), - }, - }), - ]); - - const gotSubCount = topSubInstances - .map((x) => x.followersCount) - .reduce((a, b) => a + b, 0); - const gotPubCount = topPubInstances - .map((x) => x.followingCount) - .reduce((a, b) => a + b, 0); - - return await awaitAll({ - topSubInstances: Instances.packMany(topSubInstances), - otherFollowersCount: Math.max(0, allSubCount - gotSubCount), - topPubInstances: Instances.packMany(topPubInstances), - otherFollowingCount: Math.max(0, allPubCount - gotPubCount), - }); -}); diff --git a/packages/backend/src/server/api/endpoints/federation/update-remote-user.ts b/packages/backend/src/server/api/endpoints/federation/update-remote-user.ts deleted file mode 100644 index f4c3f6d18c..0000000000 --- a/packages/backend/src/server/api/endpoints/federation/update-remote-user.ts +++ /dev/null @@ -1,22 +0,0 @@ -import define from "../../define.js"; -import { getRemoteUser } from "../../common/getters.js"; -import { updatePerson } from "@/remote/activitypub/models/person.js"; - -export const meta = { - tags: ["federation"], - - requireCredential: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps) => { - const user = await getRemoteUser(ps.userId); - await updatePerson(user.uri!); -}); diff --git a/packages/backend/src/server/api/endpoints/federation/users.ts b/packages/backend/src/server/api/endpoints/federation/users.ts deleted file mode 100644 index ded0a26c5f..0000000000 --- a/packages/backend/src/server/api/endpoints/federation/users.ts +++ /dev/null @@ -1,45 +0,0 @@ -import define from "../../define.js"; -import { Users } from "@/models/index.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["federation"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "UserDetailedNotMe", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - host: { type: "string" }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - }, - required: ["host"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = makePaginationQuery( - Users.createQueryBuilder("user"), - ps.sinceId, - ps.untilId, - ).andWhere("user.host = :host", { host: ps.host }); - - const users = await query.take(ps.limit).getMany(); - - return await Users.packMany(users, me, { detail: true }); -}); diff --git a/packages/backend/src/server/api/endpoints/fetch-rss.ts b/packages/backend/src/server/api/endpoints/fetch-rss.ts deleted file mode 100644 index b73d7262c9..0000000000 --- a/packages/backend/src/server/api/endpoints/fetch-rss.ts +++ /dev/null @@ -1,38 +0,0 @@ -import Parser from "rss-parser"; -import { getResponse } from "@/misc/fetch.js"; -import config from "@/config/index.js"; -import define from "../define.js"; - -const rssParser = new Parser(); - -export const meta = { - tags: ["meta"], - - requireCredential: false, - allowGet: true, - cacheSec: 60 * 3, -} as const; - -export const paramDef = { - type: "object", - properties: { - url: { type: "string" }, - }, - required: ["url"], -} as const; - -export default define(meta, paramDef, async (ps) => { - const res = await getResponse({ - url: ps.url, - method: "GET", - headers: Object.assign({ - "User-Agent": config.userAgent, - Accept: "application/rss+xml, */*", - }), - timeout: 5000, - }); - - const text = await res.text(); - - return rssParser.parseString(text); -}); diff --git a/packages/backend/src/server/api/endpoints/following/create.ts b/packages/backend/src/server/api/endpoints/following/create.ts deleted file mode 100644 index e617c1ffb3..0000000000 --- a/packages/backend/src/server/api/endpoints/following/create.ts +++ /dev/null @@ -1,107 +0,0 @@ -import create from "@/services/following/create.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { getUser } from "../../common/getters.js"; -import { Followings, Users } from "@/models/index.js"; -import { IdentifiableError } from "@/misc/identifiable-error.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - tags: ["following", "users"], - - limit: { - duration: HOUR, - max: 100, - }, - - requireCredential: true, - - kind: "write:following", - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "fcd2eef9-a9b2-4c4f-8624-038099e90aa5", - }, - - followeeIsYourself: { - message: "Followee is yourself.", - code: "FOLLOWEE_IS_YOURSELF", - id: "26fbe7bb-a331-4857-af17-205b426669a9", - }, - - alreadyFollowing: { - message: "You are already following that user.", - code: "ALREADY_FOLLOWING", - id: "35387507-38c7-4cb9-9197-300b93783fa0", - }, - - blocking: { - message: "You are blocking that user.", - code: "BLOCKING", - id: "4e2206ec-aa4f-4960-b865-6c23ac38e2d9", - }, - - blocked: { - message: "You are blocked by that user.", - code: "BLOCKED", - id: "c4ab57cc-4e41-45e9-bfd9-584f61e35ce0", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "UserLite", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const follower = user; - - // 自分自身 - if (user.id === ps.userId) { - throw new ApiError(meta.errors.followeeIsYourself); - } - - // Get followee - const followee = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - // Check if already following - const exist = await Followings.findOneBy({ - followerId: follower.id, - followeeId: followee.id, - }); - - if (exist != null) { - throw new ApiError(meta.errors.alreadyFollowing); - } - - try { - await create(follower, followee); - } catch (e) { - if (e instanceof IdentifiableError) { - if (e.id === "710e8fb0-b8c3-4922-be49-d5d93d8e6a6e") - throw new ApiError(meta.errors.blocking); - if (e.id === "3338392a-f764-498d-8855-db939dcf8c48") - throw new ApiError(meta.errors.blocked); - } - throw e; - } - - return await Users.pack(followee.id, user); -}); diff --git a/packages/backend/src/server/api/endpoints/following/delete.ts b/packages/backend/src/server/api/endpoints/following/delete.ts deleted file mode 100644 index 2eebe8a903..0000000000 --- a/packages/backend/src/server/api/endpoints/following/delete.ts +++ /dev/null @@ -1,84 +0,0 @@ -import deleteFollowing from "@/services/following/delete.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { getUser } from "../../common/getters.js"; -import { Followings, Users } from "@/models/index.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - tags: ["following", "users"], - - limit: { - duration: HOUR, - max: 100, - }, - - requireCredential: true, - - kind: "write:following", - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "5b12c78d-2b28-4dca-99d2-f56139b42ff8", - }, - - followeeIsYourself: { - message: "Followee is yourself.", - code: "FOLLOWEE_IS_YOURSELF", - id: "d9e400b9-36b0-4808-b1d8-79e707f1296c", - }, - - notFollowing: { - message: "You are not following that user.", - code: "NOT_FOLLOWING", - id: "5dbf82f5-c92b-40b1-87d1-6c8c0741fd09", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "UserLite", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const follower = user; - - // Check if the followee is yourself - if (user.id === ps.userId) { - throw new ApiError(meta.errors.followeeIsYourself); - } - - // Get followee - const followee = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - // Check not following - const exist = await Followings.findOneBy({ - followerId: follower.id, - followeeId: followee.id, - }); - - if (exist == null) { - throw new ApiError(meta.errors.notFollowing); - } - - await deleteFollowing(follower, followee); - - return await Users.pack(followee.id, user); -}); diff --git a/packages/backend/src/server/api/endpoints/following/invalidate.ts b/packages/backend/src/server/api/endpoints/following/invalidate.ts deleted file mode 100644 index 979d298f7d..0000000000 --- a/packages/backend/src/server/api/endpoints/following/invalidate.ts +++ /dev/null @@ -1,84 +0,0 @@ -import deleteFollowing from "@/services/following/delete.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { getUser } from "../../common/getters.js"; -import { Followings, Users } from "@/models/index.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - tags: ["following", "users"], - - limit: { - duration: HOUR, - max: 100, - }, - - requireCredential: true, - - kind: "write:following", - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "5b12c78d-2b28-4dca-99d2-f56139b42ff8", - }, - - followerIsYourself: { - message: "Follower is yourself.", - code: "FOLLOWER_IS_YOURSELF", - id: "07dc03b9-03da-422d-885b-438313707662", - }, - - notFollowing: { - message: "The other use is not following you.", - code: "NOT_FOLLOWING", - id: "5dbf82f5-c92b-40b1-87d1-6c8c0741fd09", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "UserLite", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const followee = user; - - // Check if the follower is yourself - if (user.id === ps.userId) { - throw new ApiError(meta.errors.followerIsYourself); - } - - // Get follower - const follower = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - // Check not following - const exist = await Followings.findOneBy({ - followerId: follower.id, - followeeId: followee.id, - }); - - if (exist == null) { - throw new ApiError(meta.errors.notFollowing); - } - - await deleteFollowing(follower, followee); - - return await Users.pack(followee.id, user); -}); diff --git a/packages/backend/src/server/api/endpoints/following/requests/accept.ts b/packages/backend/src/server/api/endpoints/following/requests/accept.ts deleted file mode 100644 index a4fc052367..0000000000 --- a/packages/backend/src/server/api/endpoints/following/requests/accept.ts +++ /dev/null @@ -1,50 +0,0 @@ -import acceptFollowRequest from "@/services/following/requests/accept.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { getUser } from "../../../common/getters.js"; - -export const meta = { - tags: ["following", "account"], - - requireCredential: true, - - kind: "write:following", - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "66ce1645-d66c-46bb-8b79-96739af885bd", - }, - noFollowRequest: { - message: "No follow request.", - code: "NO_FOLLOW_REQUEST", - id: "bcde4f8b-0913-4614-8881-614e522fb041", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Fetch follower - const follower = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - await acceptFollowRequest(user, follower).catch((e) => { - if (e.id === "8884c2dd-5795-4ac9-b27e-6a01d38190f9") - throw new ApiError(meta.errors.noFollowRequest); - throw e; - }); - - return; -}); diff --git a/packages/backend/src/server/api/endpoints/following/requests/cancel.ts b/packages/backend/src/server/api/endpoints/following/requests/cancel.ts deleted file mode 100644 index f309e32999..0000000000 --- a/packages/backend/src/server/api/endpoints/following/requests/cancel.ts +++ /dev/null @@ -1,64 +0,0 @@ -import cancelFollowRequest from "@/services/following/requests/cancel.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { getUser } from "../../../common/getters.js"; -import { Users } from "@/models/index.js"; -import { IdentifiableError } from "@/misc/identifiable-error.js"; - -export const meta = { - tags: ["following", "account"], - - requireCredential: true, - - kind: "write:following", - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "4e68c551-fc4c-4e46-bb41-7d4a37bf9dab", - }, - - followRequestNotFound: { - message: "Follow request not found.", - code: "FOLLOW_REQUEST_NOT_FOUND", - id: "089b125b-d338-482a-9a09-e2622ac9f8d4", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "UserLite", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Fetch followee - const followee = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - try { - await cancelFollowRequest(followee, user); - } catch (e) { - if (e instanceof IdentifiableError) { - if (e.id === "17447091-ce07-46dd-b331-c1fd4f15b1e7") - throw new ApiError(meta.errors.followRequestNotFound); - } - throw e; - } - - return await Users.pack(followee.id, user); -}); diff --git a/packages/backend/src/server/api/endpoints/following/requests/list.ts b/packages/backend/src/server/api/endpoints/following/requests/list.ts deleted file mode 100644 index 6ba23de585..0000000000 --- a/packages/backend/src/server/api/endpoints/following/requests/list.ts +++ /dev/null @@ -1,55 +0,0 @@ -import define from "../../../define.js"; -import { FollowRequests } from "@/models/index.js"; - -export const meta = { - tags: ["following", "account"], - - requireCredential: true, - - kind: "read:following", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - follower: { - type: "object", - optional: false, - nullable: false, - ref: "UserLite", - }, - followee: { - type: "object", - optional: false, - nullable: false, - ref: "UserLite", - }, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const reqs = await FollowRequests.findBy({ - followeeId: user.id, - }); - - return await Promise.all(reqs.map((req) => FollowRequests.pack(req))); -}); diff --git a/packages/backend/src/server/api/endpoints/following/requests/reject.ts b/packages/backend/src/server/api/endpoints/following/requests/reject.ts deleted file mode 100644 index fedc0db487..0000000000 --- a/packages/backend/src/server/api/endpoints/following/requests/reject.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { rejectFollowRequest } from "@/services/following/reject.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { getUser } from "../../../common/getters.js"; - -export const meta = { - tags: ["following", "account"], - - requireCredential: true, - - kind: "write:following", - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "abc2ffa6-25b2-4380-ba99-321ff3a94555", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Fetch follower - const follower = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - await rejectFollowRequest(user, follower); - - return; -}); diff --git a/packages/backend/src/server/api/endpoints/gallery/featured.ts b/packages/backend/src/server/api/endpoints/gallery/featured.ts deleted file mode 100644 index d478e8e3bf..0000000000 --- a/packages/backend/src/server/api/endpoints/gallery/featured.ts +++ /dev/null @@ -1,40 +0,0 @@ -import define from "../../define.js"; -import { GalleryPosts } from "@/models/index.js"; - -export const meta = { - tags: ["gallery"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "GalleryPost", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = GalleryPosts.createQueryBuilder("post") - .andWhere("post.createdAt > :date", { - date: new Date(Date.now() - 1000 * 60 * 60 * 24 * 3), - }) - .andWhere("post.likedCount > 0") - .orderBy("post.likedCount", "DESC"); - - const posts = await query.take(10).getMany(); - - return await GalleryPosts.packMany(posts, me); -}); diff --git a/packages/backend/src/server/api/endpoints/gallery/popular.ts b/packages/backend/src/server/api/endpoints/gallery/popular.ts deleted file mode 100644 index 5eef68d971..0000000000 --- a/packages/backend/src/server/api/endpoints/gallery/popular.ts +++ /dev/null @@ -1,37 +0,0 @@ -import define from "../../define.js"; -import { GalleryPosts } from "@/models/index.js"; - -export const meta = { - tags: ["gallery"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "GalleryPost", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = GalleryPosts.createQueryBuilder("post") - .andWhere("post.likedCount > 0") - .orderBy("post.likedCount", "DESC"); - - const posts = await query.take(10).getMany(); - - return await GalleryPosts.packMany(posts, me); -}); diff --git a/packages/backend/src/server/api/endpoints/gallery/posts.ts b/packages/backend/src/server/api/endpoints/gallery/posts.ts deleted file mode 100644 index f97c161aff..0000000000 --- a/packages/backend/src/server/api/endpoints/gallery/posts.ts +++ /dev/null @@ -1,42 +0,0 @@ -import define from "../../define.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { GalleryPosts } from "@/models/index.js"; - -export const meta = { - tags: ["gallery"], - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "GalleryPost", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = makePaginationQuery( - GalleryPosts.createQueryBuilder("post"), - ps.sinceId, - ps.untilId, - ).innerJoinAndSelect("post.user", "user"); - - const posts = await query.take(ps.limit).getMany(); - - return await GalleryPosts.packMany(posts, me); -}); diff --git a/packages/backend/src/server/api/endpoints/gallery/posts/create.ts b/packages/backend/src/server/api/endpoints/gallery/posts/create.ts deleted file mode 100644 index f3b3768e28..0000000000 --- a/packages/backend/src/server/api/endpoints/gallery/posts/create.ts +++ /dev/null @@ -1,81 +0,0 @@ -import define from "../../../define.js"; -import { DriveFiles, GalleryPosts } from "@/models/index.js"; -import { genId } from "../../../../../misc/gen-id.js"; -import { GalleryPost } from "@/models/entities/gallery-post.js"; -import { ApiError } from "../../../error.js"; -import type { DriveFile } from "@/models/entities/drive-file.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - tags: ["gallery"], - - requireCredential: true, - - kind: "write:gallery", - - limit: { - duration: HOUR, - max: 300, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "GalleryPost", - }, - - errors: {}, -} as const; - -export const paramDef = { - type: "object", - properties: { - title: { type: "string", minLength: 1 }, - description: { type: "string", nullable: true }, - fileIds: { - type: "array", - uniqueItems: true, - minItems: 1, - maxItems: 32, - items: { - type: "string", - format: "misskey:id", - }, - }, - isSensitive: { type: "boolean", default: false }, - }, - required: ["title", "fileIds"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const files = ( - await Promise.all( - ps.fileIds.map((fileId) => - DriveFiles.findOneBy({ - id: fileId, - userId: user.id, - }), - ), - ) - ).filter((file): file is DriveFile => file != null); - - if (files.length === 0) { - throw new Error(); - } - - const post = await GalleryPosts.insert( - new GalleryPost({ - id: genId(), - createdAt: new Date(), - updatedAt: new Date(), - title: ps.title, - description: ps.description, - userId: user.id, - isSensitive: ps.isSensitive, - fileIds: files.map((file) => file.id), - }), - ).then((x) => GalleryPosts.findOneByOrFail(x.identifiers[0])); - - return await GalleryPosts.pack(post, user); -}); diff --git a/packages/backend/src/server/api/endpoints/gallery/posts/delete.ts b/packages/backend/src/server/api/endpoints/gallery/posts/delete.ts deleted file mode 100644 index 9fd9a50099..0000000000 --- a/packages/backend/src/server/api/endpoints/gallery/posts/delete.ts +++ /dev/null @@ -1,40 +0,0 @@ -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { GalleryPosts } from "@/models/index.js"; - -export const meta = { - tags: ["gallery"], - - requireCredential: true, - - kind: "write:gallery", - - errors: { - noSuchPost: { - message: "No such post.", - code: "NO_SUCH_POST", - id: "ae52f367-4bd7-4ecd-afc6-5672fff427f5", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - postId: { type: "string", format: "misskey:id" }, - }, - required: ["postId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const post = await GalleryPosts.findOneBy({ - id: ps.postId, - userId: user.id, - }); - - if (post == null) { - throw new ApiError(meta.errors.noSuchPost); - } - - await GalleryPosts.delete(post.id); -}); diff --git a/packages/backend/src/server/api/endpoints/gallery/posts/like.ts b/packages/backend/src/server/api/endpoints/gallery/posts/like.ts deleted file mode 100644 index fd46406bdf..0000000000 --- a/packages/backend/src/server/api/endpoints/gallery/posts/like.ts +++ /dev/null @@ -1,61 +0,0 @@ -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { GalleryPosts, GalleryLikes } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; - -export const meta = { - tags: ["gallery"], - - requireCredential: true, - - kind: "write:gallery-likes", - - errors: { - noSuchPost: { - message: "No such post.", - code: "NO_SUCH_POST", - id: "56c06af3-1287-442f-9701-c93f7c4a62ff", - }, - - alreadyLiked: { - message: "The post has already been liked.", - code: "ALREADY_LIKED", - id: "40e9ed56-a59c-473a-bf3f-f289c54fb5a7", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - postId: { type: "string", format: "misskey:id" }, - }, - required: ["postId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const post = await GalleryPosts.findOneBy({ id: ps.postId }); - if (post == null) { - throw new ApiError(meta.errors.noSuchPost); - } - - // if already liked - const exist = await GalleryLikes.findOneBy({ - postId: post.id, - userId: user.id, - }); - - if (exist != null) { - throw new ApiError(meta.errors.alreadyLiked); - } - - // Create like - await GalleryLikes.insert({ - id: genId(), - createdAt: new Date(), - postId: post.id, - userId: user.id, - }); - - GalleryPosts.increment({ id: post.id }, "likedCount", 1); -}); diff --git a/packages/backend/src/server/api/endpoints/gallery/posts/show.ts b/packages/backend/src/server/api/endpoints/gallery/posts/show.ts deleted file mode 100644 index 87e272f018..0000000000 --- a/packages/backend/src/server/api/endpoints/gallery/posts/show.ts +++ /dev/null @@ -1,45 +0,0 @@ -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { GalleryPosts } from "@/models/index.js"; - -export const meta = { - tags: ["gallery"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - errors: { - noSuchPost: { - message: "No such post.", - code: "NO_SUCH_POST", - id: "1137bf14-c5b0-4604-85bb-5b5371b1cd45", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "GalleryPost", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - postId: { type: "string", format: "misskey:id" }, - }, - required: ["postId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const post = await GalleryPosts.findOneBy({ - id: ps.postId, - }); - - if (post == null) { - throw new ApiError(meta.errors.noSuchPost); - } - - return await GalleryPosts.pack(post, me); -}); diff --git a/packages/backend/src/server/api/endpoints/gallery/posts/unlike.ts b/packages/backend/src/server/api/endpoints/gallery/posts/unlike.ts deleted file mode 100644 index 772dc92028..0000000000 --- a/packages/backend/src/server/api/endpoints/gallery/posts/unlike.ts +++ /dev/null @@ -1,54 +0,0 @@ -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { GalleryPosts, GalleryLikes } from "@/models/index.js"; - -export const meta = { - tags: ["gallery"], - - requireCredential: true, - - kind: "write:gallery-likes", - - errors: { - noSuchPost: { - message: "No such post.", - code: "NO_SUCH_POST", - id: "c32e6dd0-b555-4413-925e-b3757d19ed84", - }, - - notLiked: { - message: "You have not liked that post.", - code: "NOT_LIKED", - id: "e3e8e06e-be37-41f7-a5b4-87a8250288f0", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - postId: { type: "string", format: "misskey:id" }, - }, - required: ["postId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const post = await GalleryPosts.findOneBy({ id: ps.postId }); - if (post == null) { - throw new ApiError(meta.errors.noSuchPost); - } - - const exist = await GalleryLikes.findOneBy({ - postId: post.id, - userId: user.id, - }); - - if (exist == null) { - throw new ApiError(meta.errors.notLiked); - } - - // Delete like - await GalleryLikes.delete(exist.id); - - GalleryPosts.decrement({ id: post.id }, "likedCount", 1); -}); diff --git a/packages/backend/src/server/api/endpoints/gallery/posts/update.ts b/packages/backend/src/server/api/endpoints/gallery/posts/update.ts deleted file mode 100644 index 64e204172e..0000000000 --- a/packages/backend/src/server/api/endpoints/gallery/posts/update.ts +++ /dev/null @@ -1,84 +0,0 @@ -import define from "../../../define.js"; -import { DriveFiles, GalleryPosts } from "@/models/index.js"; -import { GalleryPost } from "@/models/entities/gallery-post.js"; -import { ApiError } from "../../../error.js"; -import type { DriveFile } from "@/models/entities/drive-file.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - tags: ["gallery"], - - requireCredential: true, - - kind: "write:gallery", - - limit: { - duration: HOUR, - max: 300, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "GalleryPost", - }, - - errors: {}, -} as const; - -export const paramDef = { - type: "object", - properties: { - postId: { type: "string", format: "misskey:id" }, - title: { type: "string", minLength: 1 }, - description: { type: "string", nullable: true }, - fileIds: { - type: "array", - uniqueItems: true, - minItems: 1, - maxItems: 32, - items: { - type: "string", - format: "misskey:id", - }, - }, - isSensitive: { type: "boolean", default: false }, - }, - required: ["postId", "title", "fileIds"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const files = ( - await Promise.all( - ps.fileIds.map((fileId) => - DriveFiles.findOneBy({ - id: fileId, - userId: user.id, - }), - ), - ) - ).filter((file): file is DriveFile => file != null); - - if (files.length === 0) { - throw new Error(); - } - - await GalleryPosts.update( - { - id: ps.postId, - userId: user.id, - }, - { - updatedAt: new Date(), - title: ps.title, - description: ps.description, - isSensitive: ps.isSensitive, - fileIds: files.map((file) => file.id), - }, - ); - - const post = await GalleryPosts.findOneByOrFail({ id: ps.postId }); - - return await GalleryPosts.pack(post, user); -}); diff --git a/packages/backend/src/server/api/endpoints/get-online-users-count.ts b/packages/backend/src/server/api/endpoints/get-online-users-count.ts deleted file mode 100644 index 805674a5b7..0000000000 --- a/packages/backend/src/server/api/endpoints/get-online-users-count.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { MoreThan } from "typeorm"; -import { USER_ONLINE_THRESHOLD } from "@/const.js"; -import { Users } from "@/models/index.js"; -import define from "../define.js"; - -export const meta = { - tags: ["meta"], - - requireCredential: false, - requireCredentialPrivateMode: true, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - const count = await Users.countBy({ - lastActiveDate: MoreThan(new Date(Date.now() - USER_ONLINE_THRESHOLD)), - }); - - return { - count, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/get-sounds.ts b/packages/backend/src/server/api/endpoints/get-sounds.ts deleted file mode 100644 index f7edd38609..0000000000 --- a/packages/backend/src/server/api/endpoints/get-sounds.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { readdir } from "fs/promises"; -import define from "../define.js"; - -export const meta = { - tags: ["meta"], - requireCredential: false, - requireCredentialPrivateMode: false, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - const music_files: (string | null)[] = [null]; - const directory = ( - await readdir("./assets/sounds", { withFileTypes: true }) - ).filter((potentialFolder) => potentialFolder.isDirectory()); - for await (const folder of directory) { - const files = (await readdir(`./assets/sounds/${folder.name}`)).filter( - (potentialSong) => potentialSong.endsWith(".mp3"), - ); - for await (const file of files) { - music_files.push(`${folder.name}/${file.replace(".mp3", "")}`); - } - } - return music_files; -}); diff --git a/packages/backend/src/server/api/endpoints/hashtags/list.ts b/packages/backend/src/server/api/endpoints/hashtags/list.ts deleted file mode 100644 index df99a1e5a6..0000000000 --- a/packages/backend/src/server/api/endpoints/hashtags/list.ts +++ /dev/null @@ -1,112 +0,0 @@ -import define from "../../define.js"; -import { Hashtags } from "@/models/index.js"; - -export const meta = { - tags: ["hashtags"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Hashtag", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - attachedToUserOnly: { type: "boolean", default: false }, - attachedToLocalUserOnly: { type: "boolean", default: false }, - attachedToRemoteUserOnly: { type: "boolean", default: false }, - sort: { - type: "string", - enum: [ - "+mentionedUsers", - "-mentionedUsers", - "+mentionedLocalUsers", - "-mentionedLocalUsers", - "+mentionedRemoteUsers", - "-mentionedRemoteUsers", - "+attachedUsers", - "-attachedUsers", - "+attachedLocalUsers", - "-attachedLocalUsers", - "+attachedRemoteUsers", - "-attachedRemoteUsers", - ], - }, - }, - required: ["sort"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = Hashtags.createQueryBuilder("tag"); - - if (ps.attachedToUserOnly) query.andWhere("tag.attachedUsersCount != 0"); - if (ps.attachedToLocalUserOnly) - query.andWhere("tag.attachedLocalUsersCount != 0"); - if (ps.attachedToRemoteUserOnly) - query.andWhere("tag.attachedRemoteUsersCount != 0"); - - switch (ps.sort) { - case "+mentionedUsers": - query.orderBy("tag.mentionedUsersCount", "DESC"); - break; - case "-mentionedUsers": - query.orderBy("tag.mentionedUsersCount", "ASC"); - break; - case "+mentionedLocalUsers": - query.orderBy("tag.mentionedLocalUsersCount", "DESC"); - break; - case "-mentionedLocalUsers": - query.orderBy("tag.mentionedLocalUsersCount", "ASC"); - break; - case "+mentionedRemoteUsers": - query.orderBy("tag.mentionedRemoteUsersCount", "DESC"); - break; - case "-mentionedRemoteUsers": - query.orderBy("tag.mentionedRemoteUsersCount", "ASC"); - break; - case "+attachedUsers": - query.orderBy("tag.attachedUsersCount", "DESC"); - break; - case "-attachedUsers": - query.orderBy("tag.attachedUsersCount", "ASC"); - break; - case "+attachedLocalUsers": - query.orderBy("tag.attachedLocalUsersCount", "DESC"); - break; - case "-attachedLocalUsers": - query.orderBy("tag.attachedLocalUsersCount", "ASC"); - break; - case "+attachedRemoteUsers": - query.orderBy("tag.attachedRemoteUsersCount", "DESC"); - break; - case "-attachedRemoteUsers": - query.orderBy("tag.attachedRemoteUsersCount", "ASC"); - break; - } - - query.select([ - "tag.name", - "tag.mentionedUsersCount", - "tag.mentionedLocalUsersCount", - "tag.mentionedRemoteUsersCount", - "tag.attachedUsersCount", - "tag.attachedLocalUsersCount", - "tag.attachedRemoteUsersCount", - ]); - - const tags = await query.take(ps.limit).getMany(); - - return Hashtags.packMany(tags); -}); diff --git a/packages/backend/src/server/api/endpoints/hashtags/search.ts b/packages/backend/src/server/api/endpoints/hashtags/search.ts deleted file mode 100644 index 95bc608ece..0000000000 --- a/packages/backend/src/server/api/endpoints/hashtags/search.ts +++ /dev/null @@ -1,42 +0,0 @@ -import define from "../../define.js"; -import { Hashtags } from "@/models/index.js"; - -export const meta = { - tags: ["hashtags"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - query: { type: "string" }, - offset: { type: "integer", default: 0 }, - }, - required: ["query"], -} as const; - -export default define(meta, paramDef, async (ps) => { - const hashtags = await Hashtags.createQueryBuilder("tag") - .where("tag.name like :q", { q: `${ps.query.toLowerCase()}%` }) - .orderBy("tag.count", "DESC") - .groupBy("tag.id") - .take(ps.limit) - .skip(ps.offset) - .getMany(); - - return hashtags.map((tag) => tag.name); -}); diff --git a/packages/backend/src/server/api/endpoints/hashtags/show.ts b/packages/backend/src/server/api/endpoints/hashtags/show.ts deleted file mode 100644 index 8cf90e4505..0000000000 --- a/packages/backend/src/server/api/endpoints/hashtags/show.ts +++ /dev/null @@ -1,45 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { Hashtags } from "@/models/index.js"; -import { normalizeForSearch } from "@/misc/normalize-for-search.js"; - -export const meta = { - tags: ["hashtags"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "Hashtag", - }, - - errors: { - noSuchHashtag: { - message: "No such hashtag.", - code: "NO_SUCH_HASHTAG", - id: "110ee688-193e-4a3a-9ecf-c167b2e6981e", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - tag: { type: "string" }, - }, - required: ["tag"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const hashtag = await Hashtags.findOneBy({ - name: normalizeForSearch(ps.tag), - }); - if (hashtag == null) { - throw new ApiError(meta.errors.noSuchHashtag); - } - - return await Hashtags.pack(hashtag); -}); diff --git a/packages/backend/src/server/api/endpoints/hashtags/trend.ts b/packages/backend/src/server/api/endpoints/hashtags/trend.ts deleted file mode 100644 index e2a8345112..0000000000 --- a/packages/backend/src/server/api/endpoints/hashtags/trend.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { Brackets } from "typeorm"; -import define from "../../define.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { Notes } from "@/models/index.js"; -import type { Note } from "@/models/entities/note.js"; -import { safeForSql } from "@/misc/safe-for-sql.js"; -import { normalizeForSearch } from "@/misc/normalize-for-search.js"; - -/* -トレンドに載るためには「『直近a分間のユニーク投稿数が今からa分前~今からb分前の間のユニーク投稿数のn倍以上』のハッシュタグの上位5位以内に入る」ことが必要 -ユニーク投稿数とはそのハッシュタグと投稿ユーザーのペアのカウントで、例えば同じユーザーが複数回同じハッシュタグを投稿してもそのハッシュタグのユニーク投稿数は1とカウントされる - -..が理想だけどPostgreSQLでどうするのか分からないので単に「直近Aの内に投稿されたユニーク投稿数が多いハッシュタグ」で妥協する -*/ - -const rangeA = 1000 * 60 * 60; // 60分 -//const rangeB = 1000 * 60 * 120; // 2時間 -//const coefficient = 1.25; // 「n倍」の部分 -//const requiredUsers = 3; // 最低何人がそのタグを投稿している必要があるか - -const max = 5; - -export const meta = { - tags: ["hashtags"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - properties: { - tag: { - type: "string", - optional: false, - nullable: false, - }, - chart: { - type: "array", - optional: false, - nullable: false, - items: { - type: "number", - optional: false, - nullable: false, - }, - }, - usersCount: { - type: "number", - optional: false, - nullable: false, - }, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - const instance = await fetchMeta(true); - const hiddenTags = instance.hiddenTags.map((t) => normalizeForSearch(t)); - - const now = new Date(); // 5分単位で丸めた現在日時 - now.setMinutes(Math.round(now.getMinutes() / 5) * 5, 0, 0); - - const tagNotes = await Notes.createQueryBuilder("note") - .where("note.createdAt > :date", { date: new Date(now.getTime() - rangeA) }) - .andWhere( - new Brackets((qb) => { - qb.where(`note.visibility = 'public'`).orWhere( - `note.visibility = 'home'`, - ); - }), - ) - .andWhere(`note.tags != '{}'`) - .select(["note.tags", "note.userId"]) - .cache(60000) // 1 min - .getMany(); - - if (tagNotes.length === 0) { - return []; - } - - const tags: { - name: string; - users: Note["userId"][]; - }[] = []; - - for (const note of tagNotes) { - for (const tag of note.tags) { - if (hiddenTags.includes(tag)) continue; - - const x = tags.find((x) => x.name === tag); - if (x) { - if (!x.users.includes(note.userId)) { - x.users.push(note.userId); - } - } else { - tags.push({ - name: tag, - users: [note.userId], - }); - } - } - } - - // タグを人気順に並べ替え - const hots = tags - .sort((a, b) => b.users.length - a.users.length) - .map((tag) => tag.name) - .slice(0, max); - - //#region 2(または3)で話題と判定されたタグそれぞれについて過去の投稿数グラフを取得する - const countPromises: Promise<number[]>[] = []; - - const range = 20; - - // 10分 - const interval = 1000 * 60 * 10; - - for (let i = 0; i < range; i++) { - countPromises.push( - Promise.all( - hots.map((tag) => - Notes.createQueryBuilder("note") - .select("count(distinct note.userId)") - .where( - `'{"${safeForSql(tag) ? tag : "aichan_kawaii"}"}' <@ note.tags`, - ) - .andWhere("note.createdAt < :lt", { - lt: new Date(now.getTime() - interval * i), - }) - .andWhere("note.createdAt > :gt", { - gt: new Date(now.getTime() - interval * (i + 1)), - }) - .cache(60000) // 1 min - .getRawOne() - .then((x) => parseInt(x.count, 10)), - ), - ), - ); - } - - const countsLog = await Promise.all(countPromises); - //#endregion - - const totalCounts = await Promise.all( - hots.map((tag) => - Notes.createQueryBuilder("note") - .select("count(distinct note.userId)") - .where(`'{"${safeForSql(tag) ? tag : "aichan_kawaii"}"}' <@ note.tags`) - .andWhere("note.createdAt > :gt", { - gt: new Date(now.getTime() - rangeA), - }) - .cache(60000 * 60) // 60 min - .getRawOne() - .then((x) => parseInt(x.count, 10)), - ), - ); - - const stats = hots.map((tag, i) => ({ - tag, - chart: countsLog.map((counts) => counts[i]), - usersCount: totalCounts[i], - })); - - return stats; -}); diff --git a/packages/backend/src/server/api/endpoints/hashtags/users.ts b/packages/backend/src/server/api/endpoints/hashtags/users.ts deleted file mode 100644 index 532c663070..0000000000 --- a/packages/backend/src/server/api/endpoints/hashtags/users.ts +++ /dev/null @@ -1,92 +0,0 @@ -import define from "../../define.js"; -import { Users } from "@/models/index.js"; -import { normalizeForSearch } from "@/misc/normalize-for-search.js"; - -export const meta = { - requireCredential: false, - requireCredentialPrivateMode: true, - - tags: ["hashtags", "users"], - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "UserDetailed", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - tag: { type: "string" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sort: { - type: "string", - enum: [ - "+follower", - "-follower", - "+createdAt", - "-createdAt", - "+updatedAt", - "-updatedAt", - ], - }, - state: { type: "string", enum: ["all", "alive"], default: "all" }, - origin: { - type: "string", - enum: ["combined", "local", "remote"], - default: "local", - }, - }, - required: ["tag", "sort"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = Users.createQueryBuilder("user").where( - ":tag = ANY(user.tags)", - { tag: normalizeForSearch(ps.tag) }, - ); - - const recent = new Date(Date.now() - 1000 * 60 * 60 * 24 * 5); - - if (ps.state === "alive") { - query.andWhere("user.updatedAt > :date", { date: recent }); - } - - if (ps.origin === "local") { - query.andWhere("user.host IS NULL"); - } else if (ps.origin === "remote") { - query.andWhere("user.host IS NOT NULL"); - } - - switch (ps.sort) { - case "+follower": - query.orderBy("user.followersCount", "DESC"); - break; - case "-follower": - query.orderBy("user.followersCount", "ASC"); - break; - case "+createdAt": - query.orderBy("user.createdAt", "DESC"); - break; - case "-createdAt": - query.orderBy("user.createdAt", "ASC"); - break; - case "+updatedAt": - query.orderBy("user.updatedAt", "DESC"); - break; - case "-updatedAt": - query.orderBy("user.updatedAt", "ASC"); - break; - } - - const users = await query.take(ps.limit).getMany(); - - return await Users.packMany(users, me, { detail: true }); -}); diff --git a/packages/backend/src/server/api/endpoints/i.ts b/packages/backend/src/server/api/endpoints/i.ts deleted file mode 100644 index 39543442c5..0000000000 --- a/packages/backend/src/server/api/endpoints/i.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { Users } from "@/models/index.js"; -import define from "../define.js"; - -export const meta = { - tags: ["account"], - - requireCredential: true, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "MeDetailed", - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user, token) => { - const isSecure = token == null; - - // ここで渡ってきている user はキャッシュされていて古い可能性もあるので id だけ渡す - return await Users.pack<true, true>(user.id, user, { - detail: true, - includeSecrets: isSecure, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/i/2fa/done.ts b/packages/backend/src/server/api/endpoints/i/2fa/done.ts deleted file mode 100644 index 1e9892f03b..0000000000 --- a/packages/backend/src/server/api/endpoints/i/2fa/done.ts +++ /dev/null @@ -1,42 +0,0 @@ -import * as speakeasy from "speakeasy"; -import define from "../../../define.js"; -import { UserProfiles } from "@/models/index.js"; - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - token: { type: "string" }, - }, - required: ["token"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const token = ps.token.replace(/\s/g, ""); - - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - if (profile.twoFactorTempSecret == null) { - throw new Error("二段階認証の設定が開始されていません"); - } - - const verified = (speakeasy as any).totp.verify({ - secret: profile.twoFactorTempSecret, - encoding: "base32", - token: token, - }); - - if (!verified) { - throw new Error("not verified"); - } - - await UserProfiles.update(user.id, { - twoFactorSecret: profile.twoFactorTempSecret, - twoFactorEnabled: true, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/i/2fa/key-done.ts b/packages/backend/src/server/api/endpoints/i/2fa/key-done.ts deleted file mode 100644 index f0581de4b4..0000000000 --- a/packages/backend/src/server/api/endpoints/i/2fa/key-done.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { promisify } from "node:util"; -import * as cbor from "cbor"; -import define from "../../../define.js"; -import { - UserProfiles, - UserSecurityKeys, - AttestationChallenges, - Users, -} from "@/models/index.js"; -import config from "@/config/index.js"; -import { procedures, hash } from "../../../2fa.js"; -import { publishMainStream } from "@/services/stream.js"; -import { comparePassword } from "@/misc/password.js"; - -const cborDecodeFirst = promisify(cbor.decodeFirst) as any; -const rpIdHashReal = hash(Buffer.from(config.hostname, "utf-8")); - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - clientDataJSON: { type: "string" }, - attestationObject: { type: "string" }, - password: { type: "string" }, - challengeId: { type: "string" }, - name: { type: "string" }, - }, - required: [ - "clientDataJSON", - "attestationObject", - "password", - "challengeId", - "name", - ], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - // Compare password - const same = await comparePassword(ps.password, profile.password!); - - if (!same) { - throw new Error("incorrect password"); - } - - if (!profile.twoFactorEnabled) { - throw new Error("2fa not enabled"); - } - - const clientData = JSON.parse(ps.clientDataJSON); - - if (clientData.type !== "webauthn.create") { - throw new Error("not a creation attestation"); - } - if (clientData.origin !== `${config.scheme}://${config.host}`) { - throw new Error("origin mismatch"); - } - - const clientDataJSONHash = hash(Buffer.from(ps.clientDataJSON, "utf-8")); - - const attestation = await cborDecodeFirst(ps.attestationObject); - - const rpIdHash = attestation.authData.slice(0, 32); - if (!rpIdHashReal.equals(rpIdHash)) { - throw new Error("rpIdHash mismatch"); - } - - const flags = attestation.authData[32]; - - if (!(flags & 1)) { - throw new Error("user not present"); - } - - const authData = Buffer.from(attestation.authData); - const credentialIdLength = authData.readUInt16BE(53); - const credentialId = authData.slice(55, 55 + credentialIdLength); - const publicKeyData = authData.slice(55 + credentialIdLength); - const publicKey: Map<number, any> = await cborDecodeFirst(publicKeyData); - if (publicKey.get(3) !== -7) { - throw new Error("alg mismatch"); - } - - if (!(procedures as any)[attestation.fmt]) { - throw new Error("unsupported fmt"); - } - - const verificationData = (procedures as any)[attestation.fmt].verify({ - attStmt: attestation.attStmt, - authenticatorData: authData, - clientDataHash: clientDataJSONHash, - credentialId, - publicKey, - rpIdHash, - }); - if (!verificationData.valid) throw new Error("signature invalid"); - - const attestationChallenge = await AttestationChallenges.findOneBy({ - userId: user.id, - id: ps.challengeId, - registrationChallenge: true, - challenge: hash(clientData.challenge).toString("hex"), - }); - - if (!attestationChallenge) { - throw new Error("non-existent challenge"); - } - - await AttestationChallenges.delete({ - userId: user.id, - id: ps.challengeId, - }); - - // Expired challenge (> 5min old) - if ( - new Date().getTime() - attestationChallenge.createdAt.getTime() >= - 5 * 60 * 1000 - ) { - throw new Error("expired challenge"); - } - - const credentialIdString = credentialId.toString("hex"); - - await UserSecurityKeys.insert({ - userId: user.id, - id: credentialIdString, - lastUsed: new Date(), - name: ps.name, - publicKey: verificationData.publicKey.toString("hex"), - }); - - // Publish meUpdated event - publishMainStream( - user.id, - "meUpdated", - await Users.pack(user.id, user, { - detail: true, - includeSecrets: true, - }), - ); - - return { - id: credentialIdString, - name: ps.name, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/i/2fa/password-less.ts b/packages/backend/src/server/api/endpoints/i/2fa/password-less.ts deleted file mode 100644 index 11b2e9a2e3..0000000000 --- a/packages/backend/src/server/api/endpoints/i/2fa/password-less.ts +++ /dev/null @@ -1,22 +0,0 @@ -import define from "../../../define.js"; -import { UserProfiles } from "@/models/index.js"; - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - value: { type: "boolean" }, - }, - required: ["value"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - await UserProfiles.update(user.id, { - usePasswordLessLogin: ps.value, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/i/2fa/register-key.ts b/packages/backend/src/server/api/endpoints/i/2fa/register-key.ts deleted file mode 100644 index a10dc9b256..0000000000 --- a/packages/backend/src/server/api/endpoints/i/2fa/register-key.ts +++ /dev/null @@ -1,61 +0,0 @@ -import define from "../../../define.js"; -import { UserProfiles, AttestationChallenges } from "@/models/index.js"; -import { promisify } from "node:util"; -import * as crypto from "node:crypto"; -import { genId } from "@/misc/gen-id.js"; -import { hash } from "../../../2fa.js"; -import { comparePassword } from "@/misc/password.js"; - -const randomBytes = promisify(crypto.randomBytes); - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - password: { type: "string" }, - }, - required: ["password"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - // Compare password - const same = await comparePassword(ps.password, profile.password!); - - if (!same) { - throw new Error("incorrect password"); - } - - // if (!profile.twoFactorEnabled) { - // throw new Error("2fa not enabled"); - // } - - // 32 byte challenge - const entropy = await randomBytes(32); - const challenge = entropy - .toString("base64") - .replace(/=/g, "") - .replace(/\+/g, "-") - .replace(/\//g, "_"); - - const challengeId = genId(); - - await AttestationChallenges.insert({ - userId: user.id, - id: challengeId, - challenge: hash(Buffer.from(challenge, "utf-8")).toString("hex"), - createdAt: new Date(), - registrationChallenge: true, - }); - - return { - challengeId, - challenge, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/i/2fa/register.ts b/packages/backend/src/server/api/endpoints/i/2fa/register.ts deleted file mode 100644 index 533035bc91..0000000000 --- a/packages/backend/src/server/api/endpoints/i/2fa/register.ts +++ /dev/null @@ -1,57 +0,0 @@ -import * as speakeasy from "speakeasy"; -import * as QRCode from "qrcode"; -import config from "@/config/index.js"; -import { UserProfiles } from "@/models/index.js"; -import define from "../../../define.js"; -import { comparePassword } from "@/misc/password.js"; - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - password: { type: "string" }, - }, - required: ["password"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - // Compare password - const same = await comparePassword(ps.password, profile.password!); - - if (!same) { - throw new Error("incorrect password"); - } - - // Generate user's secret key - const secret = speakeasy.generateSecret({ - length: 32, - }); - - await UserProfiles.update(user.id, { - twoFactorTempSecret: secret.base32, - }); - - // Get the data URL of the authenticator URL - const url = speakeasy.otpauthURL({ - secret: secret.base32, - encoding: "base32", - label: user.username, - issuer: config.host, - }); - const dataUrl = await QRCode.toDataURL(url); - - return { - qr: dataUrl, - url, - secret: secret.base32, - label: user.username, - issuer: config.host, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/i/2fa/remove-key.ts b/packages/backend/src/server/api/endpoints/i/2fa/remove-key.ts deleted file mode 100644 index 862c971e75..0000000000 --- a/packages/backend/src/server/api/endpoints/i/2fa/remove-key.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { comparePassword } from "@/misc/password.js"; -import define from "../../../define.js"; -import { UserProfiles, UserSecurityKeys, Users } from "@/models/index.js"; -import { publishMainStream } from "@/services/stream.js"; - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - password: { type: "string" }, - credentialId: { type: "string" }, - }, - required: ["password", "credentialId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - // Compare password - const same = await comparePassword(ps.password, profile.password!); - - if (!same) { - throw new Error("incorrect password"); - } - - // Make sure we only delete the user's own creds - await UserSecurityKeys.delete({ - userId: user.id, - id: ps.credentialId, - }); - - // Publish meUpdated event - publishMainStream( - user.id, - "meUpdated", - await Users.pack(user.id, user, { - detail: true, - includeSecrets: true, - }), - ); - - return {}; -}); diff --git a/packages/backend/src/server/api/endpoints/i/2fa/unregister.ts b/packages/backend/src/server/api/endpoints/i/2fa/unregister.ts deleted file mode 100644 index 57d57ff65a..0000000000 --- a/packages/backend/src/server/api/endpoints/i/2fa/unregister.ts +++ /dev/null @@ -1,33 +0,0 @@ -import define from "../../../define.js"; -import { UserProfiles } from "@/models/index.js"; -import { comparePassword } from "@/misc/password.js"; - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - password: { type: "string" }, - }, - required: ["password"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - // Compare password - const same = await comparePassword(ps.password, profile.password!); - - if (!same) { - throw new Error("incorrect password"); - } - - await UserProfiles.update(user.id, { - twoFactorSecret: null, - twoFactorEnabled: false, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/i/apps.ts b/packages/backend/src/server/api/endpoints/i/apps.ts deleted file mode 100644 index b951601949..0000000000 --- a/packages/backend/src/server/api/endpoints/i/apps.ts +++ /dev/null @@ -1,56 +0,0 @@ -import define from "../../define.js"; -import { AccessTokens } from "@/models/index.js"; - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - sort: { - type: "string", - enum: ["+createdAt", "-createdAt", "+lastUsedAt", "-lastUsedAt"], - }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = AccessTokens.createQueryBuilder("token").where( - "token.userId = :userId", - { userId: user.id }, - ); - - switch (ps.sort) { - case "+createdAt": - query.orderBy("token.createdAt", "DESC"); - break; - case "-createdAt": - query.orderBy("token.createdAt", "ASC"); - break; - case "+lastUsedAt": - query.orderBy("token.lastUsedAt", "DESC"); - break; - case "-lastUsedAt": - query.orderBy("token.lastUsedAt", "ASC"); - break; - default: - query.orderBy("token.id", "ASC"); - break; - } - - const tokens = await query.getMany(); - - return await Promise.all( - tokens.map((token) => ({ - id: token.id, - name: token.name, - createdAt: token.createdAt, - lastUsedAt: token.lastUsedAt, - permission: token.permission, - })), - ); -}); diff --git a/packages/backend/src/server/api/endpoints/i/authorized-apps.ts b/packages/backend/src/server/api/endpoints/i/authorized-apps.ts deleted file mode 100644 index f759b23037..0000000000 --- a/packages/backend/src/server/api/endpoints/i/authorized-apps.ts +++ /dev/null @@ -1,40 +0,0 @@ -import define from "../../define.js"; -import { AccessTokens, Apps } from "@/models/index.js"; - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - offset: { type: "integer", default: 0 }, - sort: { type: "string", enum: ["desc", "asc"], default: "desc" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Get tokens - const tokens = await AccessTokens.find({ - where: { - userId: user.id, - }, - take: ps.limit, - skip: ps.offset, - order: { - id: ps.sort === "asc" ? 1 : -1, - }, - }); - - return await Promise.all( - tokens.map((token) => - Apps.pack(token.appId, user, { - detail: true, - }), - ), - ); -}); diff --git a/packages/backend/src/server/api/endpoints/i/change-password.ts b/packages/backend/src/server/api/endpoints/i/change-password.ts deleted file mode 100644 index 8bbb3ad93a..0000000000 --- a/packages/backend/src/server/api/endpoints/i/change-password.ts +++ /dev/null @@ -1,36 +0,0 @@ -import define from "../../define.js"; -import { UserProfiles } from "@/models/index.js"; -import { hashPassword, comparePassword } from "@/misc/password.js"; - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - currentPassword: { type: "string" }, - newPassword: { type: "string", minLength: 1 }, - }, - required: ["currentPassword", "newPassword"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - // Compare password - const same = await comparePassword(ps.currentPassword, profile.password!); - - if (!same) { - throw new Error("incorrect password"); - } - - // Generate hash of password - const hash = await hashPassword(ps.newPassword); - - await UserProfiles.update(user.id, { - password: hash, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/i/delete-account.ts b/packages/backend/src/server/api/endpoints/i/delete-account.ts deleted file mode 100644 index 781abe0b38..0000000000 --- a/packages/backend/src/server/api/endpoints/i/delete-account.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { UserProfiles, Users } from "@/models/index.js"; -import { deleteAccount } from "@/services/delete-account.js"; -import define from "../../define.js"; -import { comparePassword } from "@/misc/password.js"; - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - password: { type: "string" }, - }, - required: ["password"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - const userDetailed = await Users.findOneByOrFail({ id: user.id }); - if (userDetailed.isDeleted) { - return; - } - - // Compare password - const same = await comparePassword(ps.password, profile.password!); - - if (!same) { - throw new Error("incorrect password"); - } - - await deleteAccount(user); -}); diff --git a/packages/backend/src/server/api/endpoints/i/export-blocking.ts b/packages/backend/src/server/api/endpoints/i/export-blocking.ts deleted file mode 100644 index 4517ad5fab..0000000000 --- a/packages/backend/src/server/api/endpoints/i/export-blocking.ts +++ /dev/null @@ -1,22 +0,0 @@ -import define from "../../define.js"; -import { createExportBlockingJob } from "@/queue/index.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - secure: true, - requireCredential: true, - limit: { - duration: HOUR, - max: 1, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - createExportBlockingJob(user); -}); diff --git a/packages/backend/src/server/api/endpoints/i/export-following.ts b/packages/backend/src/server/api/endpoints/i/export-following.ts deleted file mode 100644 index a228de8f17..0000000000 --- a/packages/backend/src/server/api/endpoints/i/export-following.ts +++ /dev/null @@ -1,25 +0,0 @@ -import define from "../../define.js"; -import { createExportFollowingJob } from "@/queue/index.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - secure: true, - requireCredential: true, - limit: { - duration: HOUR, - max: 1, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - excludeMuting: { type: "boolean", default: false }, - excludeInactive: { type: "boolean", default: false }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - createExportFollowingJob(user, ps.excludeMuting, ps.excludeInactive); -}); diff --git a/packages/backend/src/server/api/endpoints/i/export-mute.ts b/packages/backend/src/server/api/endpoints/i/export-mute.ts deleted file mode 100644 index 7bddc434d4..0000000000 --- a/packages/backend/src/server/api/endpoints/i/export-mute.ts +++ /dev/null @@ -1,22 +0,0 @@ -import define from "../../define.js"; -import { createExportMuteJob } from "@/queue/index.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - secure: true, - requireCredential: true, - limit: { - duration: HOUR, - max: 1, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - createExportMuteJob(user); -}); diff --git a/packages/backend/src/server/api/endpoints/i/export-notes.ts b/packages/backend/src/server/api/endpoints/i/export-notes.ts deleted file mode 100644 index 48506ed6d9..0000000000 --- a/packages/backend/src/server/api/endpoints/i/export-notes.ts +++ /dev/null @@ -1,22 +0,0 @@ -import define from "../../define.js"; -import { createExportNotesJob } from "@/queue/index.js"; -import { DAY } from "@/const.js"; - -export const meta = { - secure: true, - requireCredential: true, - limit: { - duration: DAY, - max: 1, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - createExportNotesJob(user); -}); diff --git a/packages/backend/src/server/api/endpoints/i/export-user-lists.ts b/packages/backend/src/server/api/endpoints/i/export-user-lists.ts deleted file mode 100644 index a71b1730b4..0000000000 --- a/packages/backend/src/server/api/endpoints/i/export-user-lists.ts +++ /dev/null @@ -1,22 +0,0 @@ -import define from "../../define.js"; -import { createExportUserListsJob } from "@/queue/index.js"; -import { MINUTE } from "@/const.js"; - -export const meta = { - secure: true, - requireCredential: true, - limit: { - duration: MINUTE, - max: 1, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - createExportUserListsJob(user); -}); diff --git a/packages/backend/src/server/api/endpoints/i/favorites.ts b/packages/backend/src/server/api/endpoints/i/favorites.ts deleted file mode 100644 index f0dbd2de6b..0000000000 --- a/packages/backend/src/server/api/endpoints/i/favorites.ts +++ /dev/null @@ -1,47 +0,0 @@ -import define from "../../define.js"; -import { NoteFavorites } from "@/models/index.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["account", "notes", "favorites"], - - requireCredential: true, - - kind: "read:favorites", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "NoteFavorite", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = makePaginationQuery( - NoteFavorites.createQueryBuilder("favorite"), - ps.sinceId, - ps.untilId, - ) - .andWhere("favorite.userId = :meId", { meId: user.id }) - .leftJoinAndSelect("favorite.note", "note"); - - const favorites = await query.take(ps.limit).getMany(); - - return await NoteFavorites.packMany(favorites, user); -}); diff --git a/packages/backend/src/server/api/endpoints/i/gallery/likes.ts b/packages/backend/src/server/api/endpoints/i/gallery/likes.ts deleted file mode 100644 index d71ee3e5a1..0000000000 --- a/packages/backend/src/server/api/endpoints/i/gallery/likes.ts +++ /dev/null @@ -1,60 +0,0 @@ -import define from "../../../define.js"; -import { GalleryLikes } from "@/models/index.js"; -import { makePaginationQuery } from "../../../common/make-pagination-query.js"; - -export const meta = { - tags: ["account", "gallery"], - - requireCredential: true, - - kind: "read:gallery-likes", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - post: { - type: "object", - optional: false, - nullable: false, - ref: "GalleryPost", - }, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = makePaginationQuery( - GalleryLikes.createQueryBuilder("like"), - ps.sinceId, - ps.untilId, - ) - .andWhere("like.userId = :meId", { meId: user.id }) - .leftJoinAndSelect("like.post", "post"); - - const likes = await query.take(ps.limit).getMany(); - - return await GalleryLikes.packMany(likes, user); -}); diff --git a/packages/backend/src/server/api/endpoints/i/gallery/posts.ts b/packages/backend/src/server/api/endpoints/i/gallery/posts.ts deleted file mode 100644 index e471731ae7..0000000000 --- a/packages/backend/src/server/api/endpoints/i/gallery/posts.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { GalleryPosts } from "@/models/index.js"; -import define from "../../../define.js"; -import { makePaginationQuery } from "../../../common/make-pagination-query.js"; - -export const meta = { - tags: ["account", "gallery"], - - requireCredential: true, - - kind: "read:gallery", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "GalleryPost", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = makePaginationQuery( - GalleryPosts.createQueryBuilder("post"), - ps.sinceId, - ps.untilId, - ).andWhere("post.userId = :meId", { meId: user.id }); - - const posts = await query.take(ps.limit).getMany(); - - return await GalleryPosts.packMany(posts, user); -}); diff --git a/packages/backend/src/server/api/endpoints/i/get-word-muted-notes-count.ts b/packages/backend/src/server/api/endpoints/i/get-word-muted-notes-count.ts deleted file mode 100644 index bd58f9257a..0000000000 --- a/packages/backend/src/server/api/endpoints/i/get-word-muted-notes-count.ts +++ /dev/null @@ -1,38 +0,0 @@ -import define from "../../define.js"; -import { MutedNotes } from "@/models/index.js"; - -export const meta = { - tags: ["account"], - - requireCredential: true, - - kind: "read:account", - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - count: { - type: "number", - optional: false, - nullable: false, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - return { - count: await MutedNotes.countBy({ - userId: user.id, - reason: "word", - }), - }; -}); diff --git a/packages/backend/src/server/api/endpoints/i/import-blocking.ts b/packages/backend/src/server/api/endpoints/i/import-blocking.ts deleted file mode 100644 index e4f1da60cc..0000000000 --- a/packages/backend/src/server/api/endpoints/i/import-blocking.ts +++ /dev/null @@ -1,60 +0,0 @@ -import define from "../../define.js"; -import { createImportBlockingJob } from "@/queue/index.js"; -import { ApiError } from "../../error.js"; -import { DriveFiles } from "@/models/index.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - secure: true, - requireCredential: true, - - limit: { - duration: HOUR, - max: 1, - }, - - errors: { - noSuchFile: { - message: "No such file.", - code: "NO_SUCH_FILE", - id: "ebb53e5f-6574-9c0c-0b92-7ca6def56d7e", - }, - - unexpectedFileType: { - message: "We need csv file.", - code: "UNEXPECTED_FILE_TYPE", - id: "b6fab7d6-d945-d67c-dfdb-32da1cd12cfe", - }, - - tooBigFile: { - message: "That file is too big.", - code: "TOO_BIG_FILE", - id: "b7fbf0b1-aeef-3b21-29ef-fadd4cb72ccf", - }, - - emptyFile: { - message: "That file is empty.", - code: "EMPTY_FILE", - id: "6f3a4dcc-f060-a707-4950-806fbdbe60d6", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - fileId: { type: "string", format: "misskey:id" }, - }, - required: ["fileId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const file = await DriveFiles.findOneBy({ id: ps.fileId }); - - if (file == null) throw new ApiError(meta.errors.noSuchFile); - //if (!file.type.endsWith('/csv')) throw new ApiError(meta.errors.unexpectedFileType); - if (file.size > 50000) throw new ApiError(meta.errors.tooBigFile); - if (file.size === 0) throw new ApiError(meta.errors.emptyFile); - - createImportBlockingJob(user, file.id); -}); diff --git a/packages/backend/src/server/api/endpoints/i/import-following.ts b/packages/backend/src/server/api/endpoints/i/import-following.ts deleted file mode 100644 index 1a6c9b565d..0000000000 --- a/packages/backend/src/server/api/endpoints/i/import-following.ts +++ /dev/null @@ -1,59 +0,0 @@ -import define from "../../define.js"; -import { createImportFollowingJob } from "@/queue/index.js"; -import { ApiError } from "../../error.js"; -import { DriveFiles } from "@/models/index.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - secure: true, - requireCredential: true, - limit: { - duratition: HOUR, - max: 1, - }, - - errors: { - noSuchFile: { - message: "No such file.", - code: "NO_SUCH_FILE", - id: "b98644cf-a5ac-4277-a502-0b8054a709a3", - }, - - unexpectedFileType: { - message: "Must be a CSV or JSON file.", - code: "UNEXPECTED_FILE_TYPE", - id: "660f3599-bce0-4f95-9dde-311fd841c183", - }, - - tooBigFile: { - message: "That file is too big.", - code: "TOO_BIG_FILE", - id: "dee9d4ed-ad07-43ed-8b34-b2856398bc60", - }, - - emptyFile: { - message: "That file is empty.", - code: "EMPTY_FILE", - id: "31a1b42c-06f7-42ae-8a38-a661c5c9f691", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - fileId: { type: "string", format: "misskey:id" }, - }, - required: ["fileId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const file = await DriveFiles.findOneBy({ id: ps.fileId }); - - if (file == null) throw new ApiError(meta.errors.noSuchFile); - //if (!file.type.endsWith('/csv')) throw new ApiError(meta.errors.unexpectedFileType); - if (file.size > 2_000_000) throw new ApiError(meta.errors.tooBigFile); - if (file.size === 0) throw new ApiError(meta.errors.emptyFile); - - createImportFollowingJob(user, file.id); -}); diff --git a/packages/backend/src/server/api/endpoints/i/import-muting.ts b/packages/backend/src/server/api/endpoints/i/import-muting.ts deleted file mode 100644 index 20d240e739..0000000000 --- a/packages/backend/src/server/api/endpoints/i/import-muting.ts +++ /dev/null @@ -1,60 +0,0 @@ -import define from "../../define.js"; -import { createImportMutingJob } from "@/queue/index.js"; -import { ApiError } from "../../error.js"; -import { DriveFiles } from "@/models/index.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - secure: true, - requireCredential: true, - - limit: { - duration: HOUR, - max: 1, - }, - - errors: { - noSuchFile: { - message: "No such file.", - code: "NO_SUCH_FILE", - id: "e674141e-bd2a-ba85-e616-aefb187c9c2a", - }, - - unexpectedFileType: { - message: "We need csv file.", - code: "UNEXPECTED_FILE_TYPE", - id: "568c6e42-c86c-ba09-c004-517f83f9f1a8", - }, - - tooBigFile: { - message: "That file is too big.", - code: "TOO_BIG_FILE", - id: "9b4ada6d-d7f7-0472-0713-4f558bd1ec9c", - }, - - emptyFile: { - message: "That file is empty.", - code: "EMPTY_FILE", - id: "d2f12af1-e7b4-feac-86a3-519548f2728e", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - fileId: { type: "string", format: "misskey:id" }, - }, - required: ["fileId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const file = await DriveFiles.findOneBy({ id: ps.fileId }); - - if (file == null) throw new ApiError(meta.errors.noSuchFile); - //if (!file.type.endsWith('/csv')) throw new ApiError(meta.errors.unexpectedFileType); - if (file.size > 50000) throw new ApiError(meta.errors.tooBigFile); - if (file.size === 0) throw new ApiError(meta.errors.emptyFile); - - createImportMutingJob(user, file.id); -}); diff --git a/packages/backend/src/server/api/endpoints/i/import-posts.ts b/packages/backend/src/server/api/endpoints/i/import-posts.ts deleted file mode 100644 index 6fdf562fdb..0000000000 --- a/packages/backend/src/server/api/endpoints/i/import-posts.ts +++ /dev/null @@ -1,44 +0,0 @@ -import define from "../../define.js"; -import { createImportPostsJob } from "@/queue/index.js"; -import { ApiError } from "../../error.js"; -import { DriveFiles } from "@/models/index.js"; -import { DAY } from "@/const.js"; - -export const meta = { - secure: true, - requireCredential: true, - limit: { - duration: DAY, - max: 1, - }, - errors: { - noSuchFile: { - message: "No such file.", - code: "NO_SUCH_FILE", - id: "e674141e-bd2a-ba85-e616-aefb187c9c2a", - }, - - emptyFile: { - message: "That file is empty.", - code: "EMPTY_FILE", - id: "d2f12af1-e7b4-feac-86a3-519548f2728e", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - fileId: { type: "string", format: "misskey:id" }, - signatureCheck: { type: "boolean" }, - }, - required: ["fileId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const file = await DriveFiles.findOneBy({ id: ps.fileId }); - - if (file == null) throw new ApiError(meta.errors.noSuchFile); - if (file.size === 0) throw new ApiError(meta.errors.emptyFile); - createImportPostsJob(user, file.id, ps.signatureCheck); -}); diff --git a/packages/backend/src/server/api/endpoints/i/import-user-lists.ts b/packages/backend/src/server/api/endpoints/i/import-user-lists.ts deleted file mode 100644 index 03b1dffbbb..0000000000 --- a/packages/backend/src/server/api/endpoints/i/import-user-lists.ts +++ /dev/null @@ -1,59 +0,0 @@ -import define from "../../define.js"; -import { createImportUserListsJob } from "@/queue/index.js"; -import { ApiError } from "../../error.js"; -import { DriveFiles } from "@/models/index.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - secure: true, - requireCredential: true, - limit: { - duration: HOUR, - max: 1, - }, - - errors: { - noSuchFile: { - message: "No such file.", - code: "NO_SUCH_FILE", - id: "ea9cc34f-c415-4bc6-a6fe-28ac40357049", - }, - - unexpectedFileType: { - message: "We need csv file.", - code: "UNEXPECTED_FILE_TYPE", - id: "a3c9edda-dd9b-4596-be6a-150ef813745c", - }, - - tooBigFile: { - message: "That file is too big.", - code: "TOO_BIG_FILE", - id: "ae6e7a22-971b-4b52-b2be-fc0b9b121fe9", - }, - - emptyFile: { - message: "That file is empty.", - code: "EMPTY_FILE", - id: "99efe367-ce6e-4d44-93f8-5fae7b040356", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - fileId: { type: "string", format: "misskey:id" }, - }, - required: ["fileId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const file = await DriveFiles.findOneBy({ id: ps.fileId }); - - if (file == null) throw new ApiError(meta.errors.noSuchFile); - //if (!file.type.endsWith('/csv')) throw new ApiError(meta.errors.unexpectedFileType); - if (file.size > 30000) throw new ApiError(meta.errors.tooBigFile); - if (file.size === 0) throw new ApiError(meta.errors.emptyFile); - - createImportUserListsJob(user, file.id); -}); diff --git a/packages/backend/src/server/api/endpoints/i/known-as.ts b/packages/backend/src/server/api/endpoints/i/known-as.ts deleted file mode 100644 index 5e86e8b955..0000000000 --- a/packages/backend/src/server/api/endpoints/i/known-as.ts +++ /dev/null @@ -1,101 +0,0 @@ -import type { User, UserDetailedNotMeOnly } from "@/models/entities/user.js"; -import { Users } from "@/models/index.js"; -import { resolveUser } from "@/remote/resolve-user.js"; -import acceptAllFollowRequests from "@/services/following/requests/accept-all.js"; -import { publishToFollowers } from "@/services/i/update.js"; -import { publishMainStream } from "@/services/stream.js"; -import { DAY } from "@/const.js"; -import { apiLogger } from "../../logger.js"; -import { UserProfiles } from "@/models/index.js"; -import config from "@/config/index.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; - -export const meta = { - tags: ["users"], - - secure: true, - requireCredential: true, - - limit: { - duration: DAY, - max: 30, - }, - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "fcd2eef9-a9b2-4c4f-8624-038099e90aa5", - }, - notRemote: { - message: "User is not remote. You can only migrate to other instances.", - code: "NOT_REMOTE", - id: "4362f8dc-731f-4ad8-a694-be2a88922a24", - }, - uriNull: { - message: "User ActivityPup URI is null.", - code: "URI_NULL", - id: "bf326f31-d430-4f97-9933-5d61e4d48a23", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - alsoKnownAs: { type: "string" }, - }, - required: ["alsoKnownAs"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - if (!ps.alsoKnownAs) throw new ApiError(meta.errors.noSuchUser); - - let unfiltered: string = ps.alsoKnownAs; - const updates = {} as Partial<User>; - - if (!unfiltered) { - updates.alsoKnownAs = null; - } else { - if (unfiltered.startsWith("acct:")) unfiltered = unfiltered.substring(5); - if (unfiltered.startsWith("@")) unfiltered = unfiltered.substring(1); - if (!unfiltered.includes("@")) throw new ApiError(meta.errors.notRemote); - - const userAddress: string[] = unfiltered.split("@"); - const knownAs = await resolveUser(userAddress[0], userAddress[1]).catch( - (e) => { - apiLogger.warn(`failed to resolve remote user: ${e}`); - throw new ApiError(meta.errors.noSuchUser); - }, - ); - - const toUrl: string | null = knownAs.uri; - if (!toUrl) { - throw new ApiError(meta.errors.uriNull); - } - if (updates.alsoKnownAs == null || updates.alsoKnownAs.length === 0) { - updates.alsoKnownAs = [toUrl]; - } else { - updates.alsoKnownAs.push(toUrl); - } - } - - await Users.update(user.id, updates); - - const iObj = await Users.pack<true, true>(user.id, user, { - detail: true, - includeSecrets: true, - }); - - // Publish meUpdated event - publishMainStream(user.id, "meUpdated", iObj); - - if (user.isLocked === false) { - acceptAllFollowRequests(user); - } - - publishToFollowers(user.id); - - return iObj; -}); diff --git a/packages/backend/src/server/api/endpoints/i/move.ts b/packages/backend/src/server/api/endpoints/i/move.ts deleted file mode 100644 index 3d947063ff..0000000000 --- a/packages/backend/src/server/api/endpoints/i/move.ts +++ /dev/null @@ -1,174 +0,0 @@ -import type { User } from "@/models/entities/user.js"; -import { resolveUser } from "@/remote/resolve-user.js"; -import { DAY } from "@/const.js"; -import DeliverManager from "@/remote/activitypub/deliver-manager.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { apiLogger } from "../../logger.js"; -import deleteFollowing from "@/services/following/delete.js"; -import create from "@/services/following/create.js"; -import { getUser } from "@/server/api/common/getters.js"; -import { Followings, Users } from "@/models/index.js"; -import { UserProfiles } from "@/models/index.js"; -import config from "@/config/index.js"; -import { publishMainStream } from "@/services/stream.js"; - -export const meta = { - tags: ["users"], - - secure: true, - requireCredential: true, - - limit: { - duration: DAY, - max: 5, - }, - - errors: { - noSuchMoveTarget: { - message: "No such move target.", - code: "NO_SUCH_MOVE_TARGET", - id: "b5c90186-4ab0-49c8-9bba-a1f76c202ba4", - }, - remoteAccountForbids: { - message: - "Remote account doesn't have proper 'Known As' alias. Did you remember to set it?", - code: "REMOTE_ACCOUNT_FORBIDS", - id: "b5c90186-4ab0-49c8-9bba-a1f766282ba4", - }, - notRemote: { - message: "User is not remote. You can only migrate to other instances.", - code: "NOT_REMOTE", - id: "4362f8dc-731f-4ad8-a694-be2a88922a24", - }, - adminForbidden: { - message: "Admins cant migrate.", - code: "NOT_ADMIN_FORBIDDEN", - id: "4362e8dc-731f-4ad8-a694-be2a88922a24", - }, - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "fcd2eef9-a9b2-4c4f-8624-038099e90aa5", - }, - uriNull: { - message: "User ActivityPup URI is null.", - code: "URI_NULL", - id: "bf326f31-d430-4f97-9933-5d61e4d48a23", - }, - localUriNull: { - message: "Local User ActivityPup URI is null.", - code: "URI_NULL", - id: "95ba11b9-90e8-43a5-ba16-7acc1ab32e71", - }, - alreadyMoved: { - message: "Account was already moved to another account.", - code: "ALREADY_MOVED", - id: "b234a14e-9ebe-4581-8000-074b3c215962", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - moveToAccount: { type: "string" }, - }, - required: ["moveToAccount"], -} as const; - -function moveActivity(toUrl: string, fromUrl: string) { - const activity = { - id: null, - actor: fromUrl, - type: "Move", - object: fromUrl, - target: toUrl, - } as any; - - return renderActivity(activity); -} - -export default define(meta, paramDef, async (ps, user) => { - if (!ps.moveToAccount) throw new ApiError(meta.errors.noSuchMoveTarget); - if (user.isAdmin) throw new ApiError(meta.errors.adminForbidden); - if (user.movedToUri) throw new ApiError(meta.errors.alreadyMoved); - - let unfiltered: string = ps.moveToAccount; - if (!unfiltered) { - throw new ApiError(meta.errors.noSuchMoveTarget); - } - - if (unfiltered.startsWith("acct:")) unfiltered = unfiltered.substring(5); - if (unfiltered.startsWith("@")) unfiltered = unfiltered.substring(1); - if (!unfiltered.includes("@")) throw new ApiError(meta.errors.notRemote); - - const userAddress: string[] = unfiltered.split("@"); - const moveTo: User = await resolveUser(userAddress[0], userAddress[1]).catch( - (e) => { - apiLogger.warn(`failed to resolve remote user: ${e}`); - throw new ApiError(meta.errors.noSuchMoveTarget); - }, - ); - let fromUrl: string | null = user.uri; - if (!fromUrl) { - fromUrl = `${config.url}/users/${user.id}`; - } - - let toUrl: string | null = moveTo.uri; - if (!toUrl) { - throw new ApiError(meta.errors.uriNull); - } - - let allowed = false; - - moveTo.alsoKnownAs?.forEach((element) => { - if (fromUrl!.includes(element)) allowed = true; - }); - - if (!(allowed && toUrl && fromUrl)) - throw new ApiError(meta.errors.remoteAccountForbids); - - const updates = {} as Partial<User>; - - if (!toUrl) toUrl = ""; - updates.movedToUri = toUrl; - - await Users.update(user.id, updates); - const iObj = await Users.pack<true, true>(user.id, user, { - detail: true, - includeSecrets: true, - }); - - const moveAct = moveActivity(toUrl, fromUrl); - const dm = new DeliverManager(user, moveAct); - dm.addFollowersRecipe(); - dm.execute(); - - // Publish meUpdated event - publishMainStream(user.id, "meUpdated", iObj); - - const followings = await Followings.findBy({ - followeeId: user.id, - }); - - followings.forEach(async (following) => { - //if follower is local - if (!following.followerHost) { - const follower = await getUser(following.followerId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - await deleteFollowing(follower!, user); - try { - await create(follower!, moveTo); - } catch (e) { - /* empty */ - } - } - }); - - return iObj; -}); diff --git a/packages/backend/src/server/api/endpoints/i/notifications.ts b/packages/backend/src/server/api/endpoints/i/notifications.ts deleted file mode 100644 index 6e1aabef7d..0000000000 --- a/packages/backend/src/server/api/endpoints/i/notifications.ts +++ /dev/null @@ -1,186 +0,0 @@ -import { Brackets } from "typeorm"; -import { - Notifications, - Followings, - Mutings, - Users, - UserProfiles, -} from "@/models/index.js"; -import { notificationTypes } from "@/types.js"; -import read from "@/services/note/read.js"; -import { readNotification } from "../../common/read-notification.js"; -import define from "../../define.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["account", "notifications"], - - requireCredential: true, - - limit: { - duration: 60000, - max: 15, - }, - - kind: "read:notifications", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Notification", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - following: { type: "boolean", default: false }, - unreadOnly: { type: "boolean", default: false }, - markAsRead: { type: "boolean", default: true }, - includeTypes: { - type: "array", - items: { - type: "string", - enum: notificationTypes, - }, - }, - excludeTypes: { - type: "array", - items: { - type: "string", - enum: notificationTypes, - }, - }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // includeTypes が空の場合はクエリしない - if (ps.includeTypes && ps.includeTypes.length === 0) { - return []; - } - // excludeTypes に全指定されている場合はクエリしない - if (notificationTypes.every((type) => ps.excludeTypes?.includes(type))) { - return []; - } - const followingQuery = Followings.createQueryBuilder("following") - .select("following.followeeId") - .where("following.followerId = :followerId", { followerId: user.id }); - - const mutingQuery = Mutings.createQueryBuilder("muting") - .select("muting.muteeId") - .where("muting.muterId = :muterId", { muterId: user.id }); - - const mutingInstanceQuery = UserProfiles.createQueryBuilder("user_profile") - .select("user_profile.mutedInstances") - .where("user_profile.userId = :muterId", { muterId: user.id }); - - const suspendedQuery = Users.createQueryBuilder("users") - .select("users.id") - .where("users.isSuspended = TRUE"); - - const query = makePaginationQuery( - Notifications.createQueryBuilder("notification"), - ps.sinceId, - ps.untilId, - ) - .andWhere("notification.notifieeId = :meId", { meId: user.id }) - .leftJoinAndSelect("notification.notifier", "notifier") - .leftJoinAndSelect("notification.note", "note") - .leftJoinAndSelect("notifier.avatar", "notifierAvatar") - .leftJoinAndSelect("notifier.banner", "notifierBanner") - .leftJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner"); - - // muted users - query.andWhere( - new Brackets((qb) => { - qb.where( - `notification.notifierId NOT IN (${mutingQuery.getQuery()})`, - ).orWhere("notification.notifierId IS NULL"); - }), - ); - query.setParameters(mutingQuery.getParameters()); - - // muted instances - query.andWhere( - new Brackets((qb) => { - qb.andWhere("notifier.host IS NULL").orWhere( - `NOT (( ${mutingInstanceQuery.getQuery()} )::jsonb ? notifier.host)`, - ); - }), - ); - query.setParameters(mutingInstanceQuery.getParameters()); - - // suspended users - query.andWhere( - new Brackets((qb) => { - qb.where( - `notification.notifierId NOT IN (${suspendedQuery.getQuery()})`, - ).orWhere("notification.notifierId IS NULL"); - }), - ); - - if (ps.following) { - query.andWhere( - `((notification.notifierId IN (${followingQuery.getQuery()})) OR (notification.notifierId = :meId))`, - { meId: user.id }, - ); - query.setParameters(followingQuery.getParameters()); - } - - if (ps.includeTypes && ps.includeTypes.length > 0) { - query.andWhere("notification.type IN (:...includeTypes)", { - includeTypes: ps.includeTypes, - }); - } else if (ps.excludeTypes && ps.excludeTypes.length > 0) { - query.andWhere("notification.type NOT IN (:...excludeTypes)", { - excludeTypes: ps.excludeTypes, - }); - } - - if (ps.unreadOnly) { - query.andWhere("notification.isRead = false"); - } - - const notifications = await query.take(ps.limit).getMany(); - - // Mark all as read - if (notifications.length > 0 && ps.markAsRead) { - readNotification( - user.id, - notifications.map((x) => x.id), - ); - } - - const notes = notifications - .filter((notification) => - ["mention", "reply", "quote"].includes(notification.type), - ) - .map((notification) => notification.note!); - - if (notes.length > 0) { - read(user.id, notes); - } - - return await Notifications.packMany(notifications, user.id); -}); diff --git a/packages/backend/src/server/api/endpoints/i/page-likes.ts b/packages/backend/src/server/api/endpoints/i/page-likes.ts deleted file mode 100644 index 1be783a061..0000000000 --- a/packages/backend/src/server/api/endpoints/i/page-likes.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { PageLikes } from "@/models/index.js"; -import define from "../../define.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["account", "pages"], - - requireCredential: true, - - kind: "read:page-likes", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - page: { - type: "object", - optional: false, - nullable: false, - ref: "Page", - }, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = makePaginationQuery( - PageLikes.createQueryBuilder("like"), - ps.sinceId, - ps.untilId, - ) - .andWhere("like.userId = :meId", { meId: user.id }) - .leftJoinAndSelect("like.page", "page"); - - const likes = await query.take(ps.limit).getMany(); - - return PageLikes.packMany(likes, user); -}); diff --git a/packages/backend/src/server/api/endpoints/i/pages.ts b/packages/backend/src/server/api/endpoints/i/pages.ts deleted file mode 100644 index 78b72e3bce..0000000000 --- a/packages/backend/src/server/api/endpoints/i/pages.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { Pages } from "@/models/index.js"; -import define from "../../define.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["account", "pages"], - - requireCredential: true, - - kind: "read:pages", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Page", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = makePaginationQuery( - Pages.createQueryBuilder("page"), - ps.sinceId, - ps.untilId, - ).andWhere("page.userId = :meId", { meId: user.id }); - - const pages = await query.take(ps.limit).getMany(); - - return await Pages.packMany(pages); -}); diff --git a/packages/backend/src/server/api/endpoints/i/pin.ts b/packages/backend/src/server/api/endpoints/i/pin.ts deleted file mode 100644 index 40aa579184..0000000000 --- a/packages/backend/src/server/api/endpoints/i/pin.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { addPinned } from "@/services/i/pin.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { Users } from "@/models/index.js"; - -export const meta = { - tags: ["account", "notes"], - - requireCredential: true, - - kind: "write:account", - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "56734f8b-3928-431e-bf80-6ff87df40cb3", - }, - - pinLimitExceeded: { - message: "You can not pin notes any more.", - code: "PIN_LIMIT_EXCEEDED", - id: "72dab508-c64d-498f-8740-a8eec1ba385a", - }, - - alreadyPinned: { - message: "That note has already been pinned.", - code: "ALREADY_PINNED", - id: "8b18c2b7-68fe-4edb-9892-c0cbaeb6c913", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "MeDetailed", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - await addPinned(user, ps.noteId).catch((e) => { - if (e.id === "70c4e51f-5bea-449c-a030-53bee3cce202") - throw new ApiError(meta.errors.noSuchNote); - if (e.id === "15a018eb-58e5-4da1-93be-330fcc5e4e1a") - throw new ApiError(meta.errors.pinLimitExceeded); - if (e.id === "23f0cf4e-59a3-4276-a91d-61a5891c1514") - throw new ApiError(meta.errors.alreadyPinned); - throw e; - }); - - return await Users.pack<true, true>(user.id, user, { - detail: true, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/i/read-all-messaging-messages.ts b/packages/backend/src/server/api/endpoints/i/read-all-messaging-messages.ts deleted file mode 100644 index 0333677275..0000000000 --- a/packages/backend/src/server/api/endpoints/i/read-all-messaging-messages.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { publishMainStream } from "@/services/stream.js"; -import define from "../../define.js"; -import { MessagingMessages, UserGroupJoinings } from "@/models/index.js"; - -export const meta = { - tags: ["account", "messaging"], - - requireCredential: true, - - kind: "write:account", -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Update documents - await MessagingMessages.update( - { - recipientId: user.id, - isRead: false, - }, - { - isRead: true, - }, - ); - - const joinings = await UserGroupJoinings.findBy({ userId: user.id }); - - await Promise.all( - joinings.map((j) => - MessagingMessages.createQueryBuilder() - .update() - .set({ - reads: (() => `array_append("reads", '${user.id}')`) as any, - }) - .where("groupId = :groupId", { groupId: j.userGroupId }) - .andWhere("userId != :userId", { userId: user.id }) - .andWhere("NOT (:userId = ANY(reads))", { userId: user.id }) - .execute(), - ), - ); - - publishMainStream(user.id, "readAllMessagingMessages"); -}); diff --git a/packages/backend/src/server/api/endpoints/i/read-all-unread-notes.ts b/packages/backend/src/server/api/endpoints/i/read-all-unread-notes.ts deleted file mode 100644 index 8a8857c83c..0000000000 --- a/packages/backend/src/server/api/endpoints/i/read-all-unread-notes.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { publishMainStream } from "@/services/stream.js"; -import define from "../../define.js"; -import { NoteUnreads } from "@/models/index.js"; - -export const meta = { - tags: ["account"], - - requireCredential: true, - - kind: "write:account", -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Remove documents - await NoteUnreads.delete({ - userId: user.id, - }); - - // 全て既読になったイベントを発行 - publishMainStream(user.id, "readAllUnreadMentions"); - publishMainStream(user.id, "readAllUnreadSpecifiedNotes"); -}); diff --git a/packages/backend/src/server/api/endpoints/i/read-announcement.ts b/packages/backend/src/server/api/endpoints/i/read-announcement.ts deleted file mode 100644 index 5218dba871..0000000000 --- a/packages/backend/src/server/api/endpoints/i/read-announcement.ts +++ /dev/null @@ -1,60 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { genId } from "@/misc/gen-id.js"; -import { AnnouncementReads, Announcements, Users } from "@/models/index.js"; -import { publishMainStream } from "@/services/stream.js"; - -export const meta = { - tags: ["account"], - - requireCredential: true, - - kind: "write:account", - - errors: { - noSuchAnnouncement: { - message: "No such announcement.", - code: "NO_SUCH_ANNOUNCEMENT", - id: "184663db-df88-4bc2-8b52-fb85f0681939", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - announcementId: { type: "string", format: "misskey:id" }, - }, - required: ["announcementId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Check if announcement exists - const announcement = await Announcements.findOneBy({ id: ps.announcementId }); - - if (announcement == null) { - throw new ApiError(meta.errors.noSuchAnnouncement); - } - - // Check if already read - const read = await AnnouncementReads.findOneBy({ - announcementId: ps.announcementId, - userId: user.id, - }); - - if (read != null) { - return; - } - - // Create read - await AnnouncementReads.insert({ - id: genId(), - createdAt: new Date(), - announcementId: ps.announcementId, - userId: user.id, - }); - - if (!(await Users.getHasUnreadAnnouncement(user.id))) { - publishMainStream(user.id, "readAllAnnouncements"); - } -}); diff --git a/packages/backend/src/server/api/endpoints/i/regenerate-token.ts b/packages/backend/src/server/api/endpoints/i/regenerate-token.ts deleted file mode 100644 index b5b34c0902..0000000000 --- a/packages/backend/src/server/api/endpoints/i/regenerate-token.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { - publishInternalEvent, - publishMainStream, - publishUserEvent, -} from "@/services/stream.js"; -import generateUserToken from "../../common/generate-native-user-token.js"; -import define from "../../define.js"; -import { Users, UserProfiles } from "@/models/index.js"; -import { comparePassword } from "@/misc/password.js"; - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - password: { type: "string" }, - }, - required: ["password"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const freshUser = await Users.findOneByOrFail({ id: user.id }); - const oldToken = freshUser.token; - - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - // Compare password - const same = await comparePassword(ps.password, profile.password!); - - if (!same) { - throw new Error("incorrect password"); - } - - const newToken = generateUserToken(); - - await Users.update(user.id, { - token: newToken, - }); - - // Publish event - publishInternalEvent("userTokenRegenerated", { - id: user.id, - oldToken, - newToken, - }); - publishMainStream(user.id, "myTokenRegenerated"); - - // Terminate streaming - setTimeout(() => { - publishUserEvent(user.id, "terminate", {}); - }, 5000); -}); diff --git a/packages/backend/src/server/api/endpoints/i/registry/get-all.ts b/packages/backend/src/server/api/endpoints/i/registry/get-all.ts deleted file mode 100644 index ee9fe7e9d5..0000000000 --- a/packages/backend/src/server/api/endpoints/i/registry/get-all.ts +++ /dev/null @@ -1,40 +0,0 @@ -import define from "../../../define.js"; -import { RegistryItems } from "@/models/index.js"; - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - scope: { - type: "array", - default: [], - items: { - type: "string", - pattern: /^[a-zA-Z0-9_]+$/.toString().slice(1, -1), - }, - }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = RegistryItems.createQueryBuilder("item") - .where("item.domain IS NULL") - .andWhere("item.userId = :userId", { userId: user.id }) - .andWhere("item.scope = :scope", { scope: ps.scope }); - - const items = await query.getMany(); - - const res = {} as Record<string, any>; - - for (const item of items) { - res[item.key] = item.value; - } - - return res; -}); diff --git a/packages/backend/src/server/api/endpoints/i/registry/get-detail.ts b/packages/backend/src/server/api/endpoints/i/registry/get-detail.ts deleted file mode 100644 index 85900bd74d..0000000000 --- a/packages/backend/src/server/api/endpoints/i/registry/get-detail.ts +++ /dev/null @@ -1,52 +0,0 @@ -import define from "../../../define.js"; -import { RegistryItems } from "@/models/index.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - requireCredential: true, - - secure: true, - - errors: { - noSuchKey: { - message: "No such key.", - code: "NO_SUCH_KEY", - id: "97a1e8e7-c0f7-47d2-957a-92e61256e01a", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - key: { type: "string" }, - scope: { - type: "array", - default: [], - items: { - type: "string", - pattern: /^[a-zA-Z0-9_]+$/.toString().slice(1, -1), - }, - }, - }, - required: ["key"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = RegistryItems.createQueryBuilder("item") - .where("item.domain IS NULL") - .andWhere("item.userId = :userId", { userId: user.id }) - .andWhere("item.key = :key", { key: ps.key }) - .andWhere("item.scope = :scope", { scope: ps.scope }); - - const item = await query.getOne(); - - if (item == null) { - throw new ApiError(meta.errors.noSuchKey); - } - - return { - updatedAt: item.updatedAt, - value: item.value, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/i/registry/get-unsecure.ts b/packages/backend/src/server/api/endpoints/i/registry/get-unsecure.ts deleted file mode 100644 index f98c6c929f..0000000000 --- a/packages/backend/src/server/api/endpoints/i/registry/get-unsecure.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { ApiError } from "../../../error.js"; -import define from "../../../define.js"; -import { RegistryItems } from "@/models/index.js"; - -export const meta = { - requireCredential: true, - - secure: false, - - errors: { - noSuchKey: { - message: "No such key.", - code: "NO_SUCH_KEY", - id: "ac3ed68a-62f0-422b-a7bc-d5e09e8f6a6a", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - key: { type: "string" }, - scope: { - type: "array", - default: [], - items: { - type: "string", - pattern: /^[a-zA-Z0-9_]+$/.toString().slice(1, -1), - }, - }, - }, - required: ["key"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - if (ps.key !== "reactions") return; - const query = RegistryItems.createQueryBuilder("item") - .where("item.domain IS NULL") - .andWhere("item.userId = :userId", { userId: user.id }) - .andWhere("item.key = :key", { key: ps.key }) - .andWhere("item.scope = :scope", { scope: ps.scope }); - - const item = await query.getOne(); - - if (item == null) { - throw new ApiError(meta.errors.noSuchKey); - } - - return item.value; -}); diff --git a/packages/backend/src/server/api/endpoints/i/registry/get.ts b/packages/backend/src/server/api/endpoints/i/registry/get.ts deleted file mode 100644 index b143b7228a..0000000000 --- a/packages/backend/src/server/api/endpoints/i/registry/get.ts +++ /dev/null @@ -1,49 +0,0 @@ -import define from "../../../define.js"; -import { RegistryItems } from "@/models/index.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - requireCredential: true, - - secure: true, - - errors: { - noSuchKey: { - message: "No such key.", - code: "NO_SUCH_KEY", - id: "ac3ed68a-62f0-422b-a7bc-d5e09e8f6a6a", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - key: { type: "string" }, - scope: { - type: "array", - default: [], - items: { - type: "string", - pattern: /^[a-zA-Z0-9_]+$/.toString().slice(1, -1), - }, - }, - }, - required: ["key"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = RegistryItems.createQueryBuilder("item") - .where("item.domain IS NULL") - .andWhere("item.userId = :userId", { userId: user.id }) - .andWhere("item.key = :key", { key: ps.key }) - .andWhere("item.scope = :scope", { scope: ps.scope }); - - const item = await query.getOne(); - - if (item == null) { - throw new ApiError(meta.errors.noSuchKey); - } - - return item.value; -}); diff --git a/packages/backend/src/server/api/endpoints/i/registry/keys-with-type.ts b/packages/backend/src/server/api/endpoints/i/registry/keys-with-type.ts deleted file mode 100644 index 23698dc53a..0000000000 --- a/packages/backend/src/server/api/endpoints/i/registry/keys-with-type.ts +++ /dev/null @@ -1,54 +0,0 @@ -import define from "../../../define.js"; -import { RegistryItems } from "@/models/index.js"; - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - scope: { - type: "array", - default: [], - items: { - type: "string", - pattern: /^[a-zA-Z0-9_]+$/.toString().slice(1, -1), - }, - }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = RegistryItems.createQueryBuilder("item") - .where("item.domain IS NULL") - .andWhere("item.userId = :userId", { userId: user.id }) - .andWhere("item.scope = :scope", { scope: ps.scope }); - - const items = await query.getMany(); - - const res = {} as Record<string, string>; - - for (const item of items) { - const type = typeof item.value; - res[item.key] = - item.value === null - ? "null" - : Array.isArray(item.value) - ? "array" - : type === "number" - ? "number" - : type === "string" - ? "string" - : type === "boolean" - ? "boolean" - : type === "object" - ? "object" - : (null as never); - } - - return res; -}); diff --git a/packages/backend/src/server/api/endpoints/i/registry/keys.ts b/packages/backend/src/server/api/endpoints/i/registry/keys.ts deleted file mode 100644 index ad7d08c5af..0000000000 --- a/packages/backend/src/server/api/endpoints/i/registry/keys.ts +++ /dev/null @@ -1,35 +0,0 @@ -import define from "../../../define.js"; -import { RegistryItems } from "@/models/index.js"; - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - scope: { - type: "array", - default: [], - items: { - type: "string", - pattern: /^[a-zA-Z0-9_]+$/.toString().slice(1, -1), - }, - }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = RegistryItems.createQueryBuilder("item") - .select("item.key") - .where("item.domain IS NULL") - .andWhere("item.userId = :userId", { userId: user.id }) - .andWhere("item.scope = :scope", { scope: ps.scope }); - - const items = await query.getMany(); - - return items.map((x) => x.key); -}); diff --git a/packages/backend/src/server/api/endpoints/i/registry/remove.ts b/packages/backend/src/server/api/endpoints/i/registry/remove.ts deleted file mode 100644 index d3793b0e20..0000000000 --- a/packages/backend/src/server/api/endpoints/i/registry/remove.ts +++ /dev/null @@ -1,49 +0,0 @@ -import define from "../../../define.js"; -import { RegistryItems } from "@/models/index.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - requireCredential: true, - - secure: true, - - errors: { - noSuchKey: { - message: "No such key.", - code: "NO_SUCH_KEY", - id: "1fac4e8a-a6cd-4e39-a4a5-3a7e11f1b019", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - key: { type: "string" }, - scope: { - type: "array", - default: [], - items: { - type: "string", - pattern: /^[a-zA-Z0-9_]+$/.toString().slice(1, -1), - }, - }, - }, - required: ["key"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = RegistryItems.createQueryBuilder("item") - .where("item.domain IS NULL") - .andWhere("item.userId = :userId", { userId: user.id }) - .andWhere("item.key = :key", { key: ps.key }) - .andWhere("item.scope = :scope", { scope: ps.scope }); - - const item = await query.getOne(); - - if (item == null) { - throw new ApiError(meta.errors.noSuchKey); - } - - await RegistryItems.remove(item); -}); diff --git a/packages/backend/src/server/api/endpoints/i/registry/scopes.ts b/packages/backend/src/server/api/endpoints/i/registry/scopes.ts deleted file mode 100644 index 3d66359c1d..0000000000 --- a/packages/backend/src/server/api/endpoints/i/registry/scopes.ts +++ /dev/null @@ -1,32 +0,0 @@ -import define from "../../../define.js"; -import { RegistryItems } from "@/models/index.js"; - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = RegistryItems.createQueryBuilder("item") - .select("item.scope") - .where("item.domain IS NULL") - .andWhere("item.userId = :userId", { userId: user.id }); - - const items = await query.getMany(); - - const res = [] as string[][]; - - for (const item of items) { - if (res.some((scope) => scope.join(".") === item.scope.join("."))) continue; - res.push(item.scope); - } - - return res; -}); diff --git a/packages/backend/src/server/api/endpoints/i/registry/set.ts b/packages/backend/src/server/api/endpoints/i/registry/set.ts deleted file mode 100644 index 7f9eebd5e0..0000000000 --- a/packages/backend/src/server/api/endpoints/i/registry/set.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { publishMainStream } from "@/services/stream.js"; -import define from "../../../define.js"; -import { RegistryItems } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - key: { type: "string", minLength: 1 }, - value: {}, - scope: { - type: "array", - default: [], - items: { - type: "string", - pattern: /^[a-zA-Z0-9_]+$/.toString().slice(1, -1), - }, - }, - }, - required: ["key", "value"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = RegistryItems.createQueryBuilder("item") - .where("item.domain IS NULL") - .andWhere("item.userId = :userId", { userId: user.id }) - .andWhere("item.key = :key", { key: ps.key }) - .andWhere("item.scope = :scope", { scope: ps.scope }); - - const existingItem = await query.getOne(); - - if (existingItem) { - await RegistryItems.update(existingItem.id, { - updatedAt: new Date(), - value: ps.value, - }); - } else { - await RegistryItems.insert({ - id: genId(), - createdAt: new Date(), - updatedAt: new Date(), - userId: user.id, - domain: null, - scope: ps.scope, - key: ps.key, - value: ps.value, - }); - } - - // TODO: サードパーティアプリが傍受出来てしまうのでどうにかする - publishMainStream(user.id, "registryUpdated", { - scope: ps.scope, - key: ps.key, - value: ps.value, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/i/revoke-token.ts b/packages/backend/src/server/api/endpoints/i/revoke-token.ts deleted file mode 100644 index 308442bf7b..0000000000 --- a/packages/backend/src/server/api/endpoints/i/revoke-token.ts +++ /dev/null @@ -1,31 +0,0 @@ -import define from "../../define.js"; -import { AccessTokens } from "@/models/index.js"; -import { publishUserEvent } from "@/services/stream.js"; - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - tokenId: { type: "string", format: "misskey:id" }, - }, - required: ["tokenId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const token = await AccessTokens.findOneBy({ id: ps.tokenId }); - - if (token) { - await AccessTokens.delete({ - id: ps.tokenId, - userId: user.id, - }); - - // Terminate streaming - publishUserEvent(user.id, "terminate"); - } -}); diff --git a/packages/backend/src/server/api/endpoints/i/signin-history.ts b/packages/backend/src/server/api/endpoints/i/signin-history.ts deleted file mode 100644 index 288b750b7b..0000000000 --- a/packages/backend/src/server/api/endpoints/i/signin-history.ts +++ /dev/null @@ -1,31 +0,0 @@ -import define from "../../define.js"; -import { Signins } from "@/models/index.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - requireCredential: true, - - secure: true, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = makePaginationQuery( - Signins.createQueryBuilder("signin"), - ps.sinceId, - ps.untilId, - ).andWhere("signin.userId = :meId", { meId: user.id }); - - const history = await query.take(ps.limit).getMany(); - - return await Promise.all(history.map((record) => Signins.pack(record))); -}); diff --git a/packages/backend/src/server/api/endpoints/i/unpin.ts b/packages/backend/src/server/api/endpoints/i/unpin.ts deleted file mode 100644 index c248eb34e5..0000000000 --- a/packages/backend/src/server/api/endpoints/i/unpin.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { removePinned } from "@/services/i/pin.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { Users } from "@/models/index.js"; - -export const meta = { - tags: ["account", "notes"], - - requireCredential: true, - - kind: "write:account", - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "454170ce-9d63-4a43-9da1-ea10afe81e21", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "MeDetailed", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - await removePinned(user, ps.noteId).catch((e) => { - if (e.id === "b302d4cf-c050-400a-bbb3-be208681f40c") - throw new ApiError(meta.errors.noSuchNote); - throw e; - }); - - return await Users.pack<true, true>(user.id, user, { - detail: true, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/i/update-email.ts b/packages/backend/src/server/api/endpoints/i/update-email.ts deleted file mode 100644 index 94ad6b3c72..0000000000 --- a/packages/backend/src/server/api/endpoints/i/update-email.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { publishMainStream } from "@/services/stream.js"; -import define from "../../define.js"; -import rndstr from "rndstr"; -import config from "@/config/index.js"; -import { Users, UserProfiles } from "@/models/index.js"; -import { sendEmail } from "@/services/send-email.js"; -import { ApiError } from "../../error.js"; -import { validateEmailForAccount } from "@/services/validate-email-for-account.js"; -import { HOUR } from "@/const.js"; -import { comparePassword } from "@/misc/password.js"; - -export const meta = { - requireCredential: true, - - secure: true, - - limit: { - duration: HOUR, - max: 3, - }, - - errors: { - incorrectPassword: { - message: "Incorrect password.", - code: "INCORRECT_PASSWORD", - id: "e54c1d7e-e7d6-4103-86b6-0a95069b4ad3", - }, - - unavailable: { - message: "Unavailable email address.", - code: "UNAVAILABLE", - id: "a2defefb-f220-8849-0af6-17f816099323", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - password: { type: "string" }, - email: { type: "string", nullable: true }, - }, - required: ["password"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - // Compare password - const same = await comparePassword(ps.password, profile.password!); - - if (!same) { - throw new ApiError(meta.errors.incorrectPassword); - } - - if (ps.email != null) { - const available = await validateEmailForAccount(ps.email); - if (!available) { - throw new ApiError(meta.errors.unavailable); - } - } - - await UserProfiles.update(user.id, { - email: ps.email, - emailVerified: false, - emailVerifyCode: null, - }); - - const iObj = await Users.pack(user.id, user, { - detail: true, - includeSecrets: true, - }); - - // Publish meUpdated event - publishMainStream(user.id, "meUpdated", iObj); - - if (ps.email != null) { - const code = rndstr("a-z0-9", 16); - - await UserProfiles.update(user.id, { - emailVerifyCode: code, - }); - - const link = `${config.url}/verify-email/${code}`; - - sendEmail( - ps.email, - "Email verification", - `To verify email, please click this link:<br><a href="${link}">${link}</a>`, - `To verify email, please click this link: ${link}`, - ); - } - - return iObj; -}); diff --git a/packages/backend/src/server/api/endpoints/i/update.ts b/packages/backend/src/server/api/endpoints/i/update.ts deleted file mode 100644 index 56ed64296b..0000000000 --- a/packages/backend/src/server/api/endpoints/i/update.ts +++ /dev/null @@ -1,307 +0,0 @@ -import RE2 from "re2"; -import * as mfm from "mfm-js"; -import { publishMainStream, publishUserEvent } from "@/services/stream.js"; -import acceptAllFollowRequests from "@/services/following/requests/accept-all.js"; -import { publishToFollowers } from "@/services/i/update.js"; -import { extractCustomEmojisFromMfm } from "@/misc/extract-custom-emojis-from-mfm.js"; -import { extractHashtags } from "@/misc/extract-hashtags.js"; -import { updateUsertags } from "@/services/update-hashtag.js"; -import { Users, DriveFiles, UserProfiles, Pages } from "@/models/index.js"; -import type { User } from "@/models/entities/user.js"; -import type { UserProfile } from "@/models/entities/user-profile.js"; -import { notificationTypes } from "@/types.js"; -import { normalizeForSearch } from "@/misc/normalize-for-search.js"; -import { langmap } from "@/misc/langmap.js"; -import { ApiError } from "../../error.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["account"], - - requireCredential: true, - - kind: "write:account", - - errors: { - noSuchAvatar: { - message: "No such avatar file.", - code: "NO_SUCH_AVATAR", - id: "539f3a45-f215-4f81-a9a8-31293640207f", - }, - - noSuchBanner: { - message: "No such banner file.", - code: "NO_SUCH_BANNER", - id: "0d8f5629-f210-41c2-9433-735831a58595", - }, - - avatarNotAnImage: { - message: "The file specified as an avatar is not an image.", - code: "AVATAR_NOT_AN_IMAGE", - id: "f419f9f8-2f4d-46b1-9fb4-49d3a2fd7191", - }, - - bannerNotAnImage: { - message: "The file specified as a banner is not an image.", - code: "BANNER_NOT_AN_IMAGE", - id: "75aedb19-2afd-4e6d-87fc-67941256fa60", - }, - - noSuchPage: { - message: "No such page.", - code: "NO_SUCH_PAGE", - id: "8e01b590-7eb9-431b-a239-860e086c408e", - }, - - invalidRegexp: { - message: "Invalid Regular Expression.", - code: "INVALID_REGEXP", - id: "0d786918-10df-41cd-8f33-8dec7d9a89a5", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "MeDetailed", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - name: { ...Users.nameSchema, nullable: true }, - description: { ...Users.descriptionSchema, nullable: true }, - location: { ...Users.locationSchema, nullable: true }, - birthday: { ...Users.birthdaySchema, nullable: true }, - lang: { - type: "string", - enum: [null, ...Object.keys(langmap)], - nullable: true, - }, - avatarId: { type: "string", format: "misskey:id", nullable: true }, - bannerId: { type: "string", format: "misskey:id", nullable: true }, - fields: { - type: "array", - minItems: 0, - maxItems: 16, - items: { - type: "object", - properties: { - name: { type: "string" }, - value: { type: "string" }, - }, - required: ["name", "value"], - }, - }, - isLocked: { type: "boolean" }, - isExplorable: { type: "boolean" }, - hideOnlineStatus: { type: "boolean" }, - publicReactions: { type: "boolean" }, - carefulBot: { type: "boolean" }, - autoAcceptFollowed: { type: "boolean" }, - noCrawle: { type: "boolean" }, - isBot: { type: "boolean" }, - isCat: { type: "boolean" }, - speakAsCat: { type: "boolean" }, - showTimelineReplies: { type: "boolean" }, - injectFeaturedNote: { type: "boolean" }, - receiveAnnouncementEmail: { type: "boolean" }, - alwaysMarkNsfw: { type: "boolean" }, - autoSensitive: { type: "boolean" }, - ffVisibility: { type: "string", enum: ["public", "followers", "private"] }, - pinnedPageId: { type: "string", format: "misskey:id", nullable: true }, - mutedWords: { type: "array" }, - mutedInstances: { - type: "array", - items: { - type: "string", - }, - }, - mutingNotificationTypes: { - type: "array", - items: { - type: "string", - enum: notificationTypes, - }, - }, - emailNotificationTypes: { - type: "array", - items: { - type: "string", - }, - }, - }, -} as const; - -export default define(meta, paramDef, async (ps, _user, token) => { - const user = await Users.findOneByOrFail({ id: _user.id }); - const isSecure = token == null; - - const updates = {} as Partial<User>; - const profileUpdates = {} as Partial<UserProfile>; - - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - if (ps.name !== undefined) updates.name = ps.name; - if (ps.description !== undefined) profileUpdates.description = ps.description; - if (ps.lang !== undefined) profileUpdates.lang = ps.lang; - if (ps.location !== undefined) profileUpdates.location = ps.location; - if (ps.birthday !== undefined) profileUpdates.birthday = ps.birthday; - if (ps.ffVisibility !== undefined) - profileUpdates.ffVisibility = ps.ffVisibility; - if (ps.avatarId !== undefined) updates.avatarId = ps.avatarId; - if (ps.bannerId !== undefined) updates.bannerId = ps.bannerId; - if (ps.mutedWords !== undefined) { - // validate regular expression syntax - ps.mutedWords - .filter((x) => !Array.isArray(x)) - .forEach((x) => { - const regexp = x.match(/^\/(.+)\/(.*)$/); - if (!regexp) throw new ApiError(meta.errors.invalidRegexp); - - try { - new RE2(regexp[1], regexp[2]); - } catch (err) { - throw new ApiError(meta.errors.invalidRegexp); - } - }); - - profileUpdates.mutedWords = ps.mutedWords; - profileUpdates.enableWordMute = ps.mutedWords.length > 0; - } - if (ps.mutedInstances !== undefined) - profileUpdates.mutedInstances = ps.mutedInstances; - if (ps.mutingNotificationTypes !== undefined) - profileUpdates.mutingNotificationTypes = - ps.mutingNotificationTypes as typeof notificationTypes[number][]; - if (typeof ps.isLocked === "boolean") updates.isLocked = ps.isLocked; - if (typeof ps.isExplorable === "boolean") - updates.isExplorable = ps.isExplorable; - if (typeof ps.hideOnlineStatus === "boolean") - updates.hideOnlineStatus = ps.hideOnlineStatus; - if (typeof ps.publicReactions === "boolean") - profileUpdates.publicReactions = ps.publicReactions; - if (typeof ps.isBot === "boolean") updates.isBot = ps.isBot; - if (typeof ps.showTimelineReplies === "boolean") - updates.showTimelineReplies = ps.showTimelineReplies; - if (typeof ps.carefulBot === "boolean") - profileUpdates.carefulBot = ps.carefulBot; - if (typeof ps.autoAcceptFollowed === "boolean") - profileUpdates.autoAcceptFollowed = ps.autoAcceptFollowed; - if (typeof ps.noCrawle === "boolean") profileUpdates.noCrawle = ps.noCrawle; - if (typeof ps.isCat === "boolean") updates.isCat = ps.isCat; - if (typeof ps.speakAsCat === "boolean") updates.speakAsCat = ps.speakAsCat; - if (typeof ps.injectFeaturedNote === "boolean") - profileUpdates.injectFeaturedNote = ps.injectFeaturedNote; - if (typeof ps.receiveAnnouncementEmail === "boolean") - profileUpdates.receiveAnnouncementEmail = ps.receiveAnnouncementEmail; - if (typeof ps.alwaysMarkNsfw === "boolean") - profileUpdates.alwaysMarkNsfw = ps.alwaysMarkNsfw; - if (typeof ps.autoSensitive === "boolean") - profileUpdates.autoSensitive = ps.autoSensitive; - if (ps.emailNotificationTypes !== undefined) - profileUpdates.emailNotificationTypes = ps.emailNotificationTypes; - - if (ps.avatarId) { - const avatar = await DriveFiles.findOneBy({ id: ps.avatarId }); - - if (avatar == null || avatar.userId !== user.id) - throw new ApiError(meta.errors.noSuchAvatar); - if (!avatar.type.startsWith("image/")) - throw new ApiError(meta.errors.avatarNotAnImage); - } - - if (ps.bannerId) { - const banner = await DriveFiles.findOneBy({ id: ps.bannerId }); - - if (banner == null || banner.userId !== user.id) - throw new ApiError(meta.errors.noSuchBanner); - if (!banner.type.startsWith("image/")) - throw new ApiError(meta.errors.bannerNotAnImage); - } - - if (ps.pinnedPageId) { - const page = await Pages.findOneBy({ id: ps.pinnedPageId }); - - if (page == null || page.userId !== user.id) - throw new ApiError(meta.errors.noSuchPage); - - profileUpdates.pinnedPageId = page.id; - } else if (ps.pinnedPageId === null) { - profileUpdates.pinnedPageId = null; - } - - if (ps.fields) { - profileUpdates.fields = ps.fields - .filter( - (x) => - typeof x.name === "string" && - x.name !== "" && - typeof x.value === "string" && - x.value !== "", - ) - .map((x) => { - return { name: x.name, value: x.value }; - }); - } - - //#region emojis/tags - - let emojis = [] as string[]; - let tags = [] as string[]; - - const newName = updates.name === undefined ? user.name : updates.name; - const newDescription = - profileUpdates.description === undefined - ? profile.description - : profileUpdates.description; - - if (newName != null) { - const tokens = mfm.parseSimple(newName); - emojis = emojis.concat(extractCustomEmojisFromMfm(tokens!)); - } - - if (newDescription != null) { - const tokens = mfm.parse(newDescription); - emojis = emojis.concat(extractCustomEmojisFromMfm(tokens!)); - tags = extractHashtags(tokens!) - .map((tag) => normalizeForSearch(tag)) - .splice(0, 32); - } - - updates.emojis = emojis; - updates.tags = tags; - - // ハッシュタグ更新 - updateUsertags(user, tags); - //#endregion - - if (Object.keys(updates).length > 0) await Users.update(user.id, updates); - if (Object.keys(profileUpdates).length > 0) - await UserProfiles.update(user.id, profileUpdates); - - const iObj = await Users.pack<true, true>(user.id, user, { - detail: true, - includeSecrets: isSecure, - }); - - // Publish meUpdated event - publishMainStream(user.id, "meUpdated", iObj); - publishUserEvent( - user.id, - "updateUserProfile", - await UserProfiles.findOneBy({ userId: user.id }), - ); - - // 鍵垢を解除したとき、溜まっていたフォローリクエストがあるならすべて承認 - if (user.isLocked && ps.isLocked === false) { - acceptAllFollowRequests(user); - } - - // フォロワーにUpdateを配信 - publishToFollowers(user.id); - - return iObj; -}); diff --git a/packages/backend/src/server/api/endpoints/i/user-group-invites.ts b/packages/backend/src/server/api/endpoints/i/user-group-invites.ts deleted file mode 100644 index d0c6caf0e2..0000000000 --- a/packages/backend/src/server/api/endpoints/i/user-group-invites.ts +++ /dev/null @@ -1,60 +0,0 @@ -import define from "../../define.js"; -import { UserGroupInvitations } from "@/models/index.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["account", "groups"], - - requireCredential: true, - - kind: "read:user-groups", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - group: { - type: "object", - optional: false, - nullable: false, - ref: "UserGroup", - }, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = makePaginationQuery( - UserGroupInvitations.createQueryBuilder("invitation"), - ps.sinceId, - ps.untilId, - ) - .andWhere("invitation.userId = :meId", { meId: user.id }) - .leftJoinAndSelect("invitation.userGroup", "user_group"); - - const invitations = await query.take(ps.limit).getMany(); - - return await UserGroupInvitations.packMany(invitations); -}); diff --git a/packages/backend/src/server/api/endpoints/i/webhooks/create.ts b/packages/backend/src/server/api/endpoints/i/webhooks/create.ts deleted file mode 100644 index 2b0f1781ea..0000000000 --- a/packages/backend/src/server/api/endpoints/i/webhooks/create.ts +++ /dev/null @@ -1,46 +0,0 @@ -import define from "../../../define.js"; -import { genId } from "@/misc/gen-id.js"; -import { Webhooks } from "@/models/index.js"; -import { publishInternalEvent } from "@/services/stream.js"; -import { webhookEventTypes } from "@/models/entities/webhook.js"; - -export const meta = { - tags: ["webhooks"], - - requireCredential: true, - - kind: "write:account", -} as const; - -export const paramDef = { - type: "object", - properties: { - name: { type: "string", minLength: 1, maxLength: 100 }, - url: { type: "string", minLength: 1, maxLength: 1024 }, - secret: { type: "string", minLength: 1, maxLength: 1024 }, - on: { - type: "array", - items: { - type: "string", - enum: webhookEventTypes, - }, - }, - }, - required: ["name", "url", "secret", "on"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const webhook = await Webhooks.insert({ - id: genId(), - createdAt: new Date(), - userId: user.id, - name: ps.name, - url: ps.url, - secret: ps.secret, - on: ps.on, - }).then((x) => Webhooks.findOneByOrFail(x.identifiers[0])); - - publishInternalEvent("webhookCreated", webhook); - - return webhook; -}); diff --git a/packages/backend/src/server/api/endpoints/i/webhooks/delete.ts b/packages/backend/src/server/api/endpoints/i/webhooks/delete.ts deleted file mode 100644 index 4a2c3d83be..0000000000 --- a/packages/backend/src/server/api/endpoints/i/webhooks/delete.ts +++ /dev/null @@ -1,43 +0,0 @@ -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { Webhooks } from "@/models/index.js"; -import { publishInternalEvent } from "@/services/stream.js"; - -export const meta = { - tags: ["webhooks"], - - requireCredential: true, - - kind: "write:account", - - errors: { - noSuchWebhook: { - message: "No such webhook.", - code: "NO_SUCH_WEBHOOK", - id: "bae73e5a-5522-4965-ae19-3a8688e71d82", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - webhookId: { type: "string", format: "misskey:id" }, - }, - required: ["webhookId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const webhook = await Webhooks.findOneBy({ - id: ps.webhookId, - userId: user.id, - }); - - if (webhook == null) { - throw new ApiError(meta.errors.noSuchWebhook); - } - - await Webhooks.delete(webhook.id); - - publishInternalEvent("webhookDeleted", webhook); -}); diff --git a/packages/backend/src/server/api/endpoints/i/webhooks/list.ts b/packages/backend/src/server/api/endpoints/i/webhooks/list.ts deleted file mode 100644 index 3afead5996..0000000000 --- a/packages/backend/src/server/api/endpoints/i/webhooks/list.ts +++ /dev/null @@ -1,24 +0,0 @@ -import define from "../../../define.js"; -import { Webhooks } from "@/models/index.js"; - -export const meta = { - tags: ["webhooks", "account"], - - requireCredential: true, - - kind: "read:account", -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const webhooks = await Webhooks.findBy({ - userId: me.id, - }); - - return webhooks; -}); diff --git a/packages/backend/src/server/api/endpoints/i/webhooks/show.ts b/packages/backend/src/server/api/endpoints/i/webhooks/show.ts deleted file mode 100644 index 96c0457475..0000000000 --- a/packages/backend/src/server/api/endpoints/i/webhooks/show.ts +++ /dev/null @@ -1,40 +0,0 @@ -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { Webhooks } from "@/models/index.js"; - -export const meta = { - tags: ["webhooks"], - - requireCredential: true, - - kind: "read:account", - - errors: { - noSuchWebhook: { - message: "No such webhook.", - code: "NO_SUCH_WEBHOOK", - id: "50f614d9-3047-4f7e-90d8-ad6b2d5fb098", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - webhookId: { type: "string", format: "misskey:id" }, - }, - required: ["webhookId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const webhook = await Webhooks.findOneBy({ - id: ps.webhookId, - userId: user.id, - }); - - if (webhook == null) { - throw new ApiError(meta.errors.noSuchWebhook); - } - - return webhook; -}); diff --git a/packages/backend/src/server/api/endpoints/i/webhooks/update.ts b/packages/backend/src/server/api/endpoints/i/webhooks/update.ts deleted file mode 100644 index 161d705e12..0000000000 --- a/packages/backend/src/server/api/endpoints/i/webhooks/update.ts +++ /dev/null @@ -1,61 +0,0 @@ -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { Webhooks } from "@/models/index.js"; -import { publishInternalEvent } from "@/services/stream.js"; -import { webhookEventTypes } from "@/models/entities/webhook.js"; - -export const meta = { - tags: ["webhooks"], - - requireCredential: true, - - kind: "write:account", - - errors: { - noSuchWebhook: { - message: "No such webhook.", - code: "NO_SUCH_WEBHOOK", - id: "fb0fea69-da18-45b1-828d-bd4fd1612518", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - webhookId: { type: "string", format: "misskey:id" }, - name: { type: "string", minLength: 1, maxLength: 100 }, - url: { type: "string", minLength: 1, maxLength: 1024 }, - secret: { type: "string", minLength: 1, maxLength: 1024 }, - on: { - type: "array", - items: { - type: "string", - enum: webhookEventTypes, - }, - }, - active: { type: "boolean" }, - }, - required: ["webhookId", "name", "url", "secret", "on", "active"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const webhook = await Webhooks.findOneBy({ - id: ps.webhookId, - userId: user.id, - }); - - if (webhook == null) { - throw new ApiError(meta.errors.noSuchWebhook); - } - - await Webhooks.update(webhook.id, { - name: ps.name, - url: ps.url, - secret: ps.secret, - on: ps.on, - active: ps.active, - }); - - publishInternalEvent("webhookUpdated", webhook); -}); diff --git a/packages/backend/src/server/api/endpoints/latest-version.ts b/packages/backend/src/server/api/endpoints/latest-version.ts deleted file mode 100644 index 72e84ae044..0000000000 --- a/packages/backend/src/server/api/endpoints/latest-version.ts +++ /dev/null @@ -1,29 +0,0 @@ -import define from "../define.js"; - -export const meta = { - tags: ["meta"], - - requireCredential: false, - requireCredentialPrivateMode: true, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - let tag_name; - await fetch( - "https://codeberg.org/api/v1/repos/calckey/calckey/releases?draft=false&pre-release=false&page=1&limit=1", - ) - .then((response) => response.json()) - .then((data) => { - tag_name = data[0].tag_name; - }); - - return { - tag_name, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/messaging/history.ts b/packages/backend/src/server/api/endpoints/messaging/history.ts deleted file mode 100644 index 7d1df69850..0000000000 --- a/packages/backend/src/server/api/endpoints/messaging/history.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { Brackets } from "typeorm"; -import type { MessagingMessage } from "@/models/entities/messaging-message.js"; -import { - MessagingMessages, - Mutings, - UserGroupJoinings, -} from "@/models/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["messaging"], - - requireCredential: true, - - kind: "read:messaging", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "MessagingMessage", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - group: { type: "boolean", default: false }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const mute = await Mutings.findBy({ - muterId: user.id, - }); - - const groups = ps.group - ? await UserGroupJoinings.findBy({ - userId: user.id, - }).then((xs) => xs.map((x) => x.userGroupId)) - : []; - - if (ps.group && groups.length === 0) { - return []; - } - - const history: MessagingMessage[] = []; - - for (let i = 0; i < ps.limit; i++) { - const found = ps.group - ? history.map((m) => m.groupId!) - : history.map((m) => (m.userId === user.id ? m.recipientId! : m.userId!)); - - const query = MessagingMessages.createQueryBuilder("message").orderBy( - "message.createdAt", - "DESC", - ); - - if (ps.group) { - query.where("message.groupId IN (:...groups)", { groups: groups }); - - if (found.length > 0) { - query.andWhere("message.groupId NOT IN (:...found)", { found: found }); - } - } else { - query.where( - new Brackets((qb) => { - qb.where("message.userId = :userId", { userId: user.id }).orWhere( - "message.recipientId = :userId", - { userId: user.id }, - ); - }), - ); - query.andWhere("message.groupId IS NULL"); - - if (found.length > 0) { - query.andWhere("message.userId NOT IN (:...found)", { found: found }); - query.andWhere("message.recipientId NOT IN (:...found)", { - found: found, - }); - } - - if (mute.length > 0) { - query.andWhere("message.userId NOT IN (:...mute)", { - mute: mute.map((m) => m.muteeId), - }); - query.andWhere("message.recipientId NOT IN (:...mute)", { - mute: mute.map((m) => m.muteeId), - }); - } - } - - const message = await query.getOne(); - - if (message) { - history.push(message); - } else { - break; - } - } - - return await Promise.all( - history.map((h) => MessagingMessages.pack(h.id, user)), - ); -}); diff --git a/packages/backend/src/server/api/endpoints/messaging/messages.ts b/packages/backend/src/server/api/endpoints/messaging/messages.ts deleted file mode 100644 index 4b5440383c..0000000000 --- a/packages/backend/src/server/api/endpoints/messaging/messages.ts +++ /dev/null @@ -1,182 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { getUser } from "../../common/getters.js"; -import { - MessagingMessages, - UserGroups, - UserGroupJoinings, - Users, -} from "@/models/index.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { Brackets } from "typeorm"; -import { - readUserMessagingMessage, - readGroupMessagingMessage, - deliverReadActivity, -} from "../../common/read-messaging-message.js"; - -export const meta = { - tags: ["messaging"], - - requireCredential: true, - - kind: "read:messaging", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "MessagingMessage", - }, - }, - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "11795c64-40ea-4198-b06e-3c873ed9039d", - }, - - noSuchGroup: { - message: "No such group.", - code: "NO_SUCH_GROUP", - id: "c4d9f88c-9270-4632-b032-6ed8cee36f7f", - }, - - groupAccessDenied: { - message: "You can not read messages of groups that you have not joined.", - code: "GROUP_ACCESS_DENIED", - id: "a053a8dd-a491-4718-8f87-50775aad9284", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - markAsRead: { type: "boolean", default: true }, - }, - anyOf: [ - { - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], - }, - { - properties: { - groupId: { type: "string", format: "misskey:id" }, - }, - required: ["groupId"], - }, - ], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - if (ps.userId != null) { - // Fetch recipient (user) - const recipient = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - const query = makePaginationQuery( - MessagingMessages.createQueryBuilder("message"), - ps.sinceId, - ps.untilId, - ) - .andWhere( - new Brackets((qb) => { - qb.where( - new Brackets((qb) => { - qb.where("message.userId = :meId").andWhere( - "message.recipientId = :recipientId", - ); - }), - ).orWhere( - new Brackets((qb) => { - qb.where("message.userId = :recipientId").andWhere( - "message.recipientId = :meId", - ); - }), - ); - }), - ) - .setParameter("meId", user.id) - .setParameter("recipientId", recipient.id); - - const messages = await query.take(ps.limit).getMany(); - - // Mark all as read - if (ps.markAsRead) { - readUserMessagingMessage( - user.id, - recipient.id, - messages.filter((m) => m.recipientId === user.id).map((x) => x.id), - ); - - // リモートユーザーとのメッセージだったら既読配信 - if (Users.isLocalUser(user) && Users.isRemoteUser(recipient)) { - deliverReadActivity(user, recipient, messages); - } - } - - return await Promise.all( - messages.map((message) => - MessagingMessages.pack(message, user, { - populateRecipient: false, - }), - ), - ); - } else if (ps.groupId != null) { - // Fetch recipient (group) - const recipientGroup = await UserGroups.findOneBy({ id: ps.groupId }); - - if (recipientGroup == null) { - throw new ApiError(meta.errors.noSuchGroup); - } - - // check joined - const joining = await UserGroupJoinings.findOneBy({ - userId: user.id, - userGroupId: recipientGroup.id, - }); - - if (joining == null) { - throw new ApiError(meta.errors.groupAccessDenied); - } - - const query = makePaginationQuery( - MessagingMessages.createQueryBuilder("message"), - ps.sinceId, - ps.untilId, - ).andWhere("message.groupId = :groupId", { groupId: recipientGroup.id }); - - const messages = await query.take(ps.limit).getMany(); - - // Mark all as read - if (ps.markAsRead) { - readGroupMessagingMessage( - user.id, - recipientGroup.id, - messages.map((x) => x.id), - ); - } - - return await Promise.all( - messages.map((message) => - MessagingMessages.pack(message, user, { - populateGroup: false, - }), - ), - ); - } -}); diff --git a/packages/backend/src/server/api/endpoints/messaging/messages/create.ts b/packages/backend/src/server/api/endpoints/messaging/messages/create.ts deleted file mode 100644 index ed9ae16df0..0000000000 --- a/packages/backend/src/server/api/endpoints/messaging/messages/create.ts +++ /dev/null @@ -1,165 +0,0 @@ -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { getUser } from "../../../common/getters.js"; -import { - MessagingMessages, - DriveFiles, - UserGroups, - UserGroupJoinings, - Blockings, -} from "@/models/index.js"; -import type { User } from "@/models/entities/user.js"; -import type { UserGroup } from "@/models/entities/user-group.js"; -import { createMessage } from "@/services/messages/create.js"; - -export const meta = { - tags: ["messaging"], - - requireCredential: true, - - kind: "write:messaging", - - res: { - type: "object", - optional: false, - nullable: false, - ref: "MessagingMessage", - }, - - errors: { - recipientIsYourself: { - message: "You can not send a message to yourself.", - code: "RECIPIENT_IS_YOURSELF", - id: "17e2ba79-e22a-4cbc-bf91-d327643f4a7e", - }, - - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "11795c64-40ea-4198-b06e-3c873ed9039d", - }, - - noSuchGroup: { - message: "No such group.", - code: "NO_SUCH_GROUP", - id: "c94e2a5d-06aa-4914-8fa6-6a42e73d6537", - }, - - groupAccessDenied: { - message: "You can not send messages to groups that you have not joined.", - code: "GROUP_ACCESS_DENIED", - id: "d96b3cca-5ad1-438b-ad8b-02f931308fbd", - }, - - noSuchFile: { - message: "No such file.", - code: "NO_SUCH_FILE", - id: "4372b8e2-185d-4146-8749-2f68864a3e5f", - }, - - contentRequired: { - message: "Content required. You need to set text or fileId.", - code: "CONTENT_REQUIRED", - id: "25587321-b0e6-449c-9239-f8925092942c", - }, - - youHaveBeenBlocked: { - message: - "You cannot send a message because you have been blocked by this user.", - code: "YOU_HAVE_BEEN_BLOCKED", - id: "c15a5199-7422-4968-941a-2a462c478f7d", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - text: { type: "string", nullable: true, maxLength: 3000 }, - fileId: { type: "string", format: "misskey:id" }, - }, - anyOf: [ - { - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], - }, - { - properties: { - groupId: { type: "string", format: "misskey:id" }, - }, - required: ["groupId"], - }, - ], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - let recipientUser: User | null; - let recipientGroup: UserGroup | null; - - if (ps.userId != null) { - // Myself - if (ps.userId === user.id) { - throw new ApiError(meta.errors.recipientIsYourself); - } - - // Fetch recipient (user) - recipientUser = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - // Check blocking - const block = await Blockings.findOneBy({ - blockerId: recipientUser.id, - blockeeId: user.id, - }); - if (block) { - throw new ApiError(meta.errors.youHaveBeenBlocked); - } - } else if (ps.groupId != null) { - // Fetch recipient (group) - recipientGroup = await UserGroups.findOneBy({ id: ps.groupId! }); - - if (recipientGroup == null) { - throw new ApiError(meta.errors.noSuchGroup); - } - - // check joined - const joining = await UserGroupJoinings.findOneBy({ - userId: user.id, - userGroupId: recipientGroup.id, - }); - - if (joining == null) { - throw new ApiError(meta.errors.groupAccessDenied); - } - } - - let file = null; - if (ps.fileId != null) { - file = await DriveFiles.findOneBy({ - id: ps.fileId, - userId: user.id, - }); - - if (file == null) { - throw new ApiError(meta.errors.noSuchFile); - } - } - - // テキストが無いかつ添付ファイルも無かったらエラー - if ((ps.text == null || ps.text.trim() === "") && file == null) { - throw new ApiError(meta.errors.contentRequired); - } - - return await createMessage( - user, - recipientUser, - recipientGroup, - ps.text, - file, - ); -}); diff --git a/packages/backend/src/server/api/endpoints/messaging/messages/delete.ts b/packages/backend/src/server/api/endpoints/messaging/messages/delete.ts deleted file mode 100644 index 42ff050d16..0000000000 --- a/packages/backend/src/server/api/endpoints/messaging/messages/delete.ts +++ /dev/null @@ -1,48 +0,0 @@ -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { MessagingMessages } from "@/models/index.js"; -import { deleteMessage } from "@/services/messages/delete.js"; -import { SECOND, HOUR } from "@/const.js"; - -export const meta = { - tags: ["messaging"], - - requireCredential: true, - - kind: "write:messaging", - - limit: { - duration: HOUR, - max: 300, - minInterval: SECOND, - }, - - errors: { - noSuchMessage: { - message: "No such message.", - code: "NO_SUCH_MESSAGE", - id: "54b5b326-7925-42cf-8019-130fda8b56af", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - messageId: { type: "string", format: "misskey:id" }, - }, - required: ["messageId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const message = await MessagingMessages.findOneBy({ - id: ps.messageId, - userId: user.id, - }); - - if (message == null) { - throw new ApiError(meta.errors.noSuchMessage); - } - - await deleteMessage(message); -}); diff --git a/packages/backend/src/server/api/endpoints/messaging/messages/read.ts b/packages/backend/src/server/api/endpoints/messaging/messages/read.ts deleted file mode 100644 index 0ef013b799..0000000000 --- a/packages/backend/src/server/api/endpoints/messaging/messages/read.ts +++ /dev/null @@ -1,57 +0,0 @@ -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { MessagingMessages } from "@/models/index.js"; -import { - readUserMessagingMessage, - readGroupMessagingMessage, -} from "../../../common/read-messaging-message.js"; - -export const meta = { - tags: ["messaging"], - - requireCredential: true, - - kind: "write:messaging", - - errors: { - noSuchMessage: { - message: "No such message.", - code: "NO_SUCH_MESSAGE", - id: "86d56a2f-a9c3-4afb-b13c-3e9bfef9aa14", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - messageId: { type: "string", format: "misskey:id" }, - }, - required: ["messageId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const message = await MessagingMessages.findOneBy({ id: ps.messageId }); - - if (message == null) { - throw new ApiError(meta.errors.noSuchMessage); - } - - if (message.recipientId) { - await readUserMessagingMessage(user.id, message.userId, [message.id]).catch( - (e) => { - if (e.id === "e140a4bf-49ce-4fb6-b67c-b78dadf6b52f") - throw new ApiError(meta.errors.noSuchMessage); - throw e; - }, - ); - } else if (message.groupId) { - await readGroupMessagingMessage(user.id, message.groupId, [ - message.id, - ]).catch((e) => { - if (e.id === "930a270c-714a-46b2-b776-ad27276dc569") - throw new ApiError(meta.errors.noSuchMessage); - throw e; - }); - } -}); diff --git a/packages/backend/src/server/api/endpoints/meta.ts b/packages/backend/src/server/api/endpoints/meta.ts deleted file mode 100644 index 4dc1c941e3..0000000000 --- a/packages/backend/src/server/api/endpoints/meta.ts +++ /dev/null @@ -1,530 +0,0 @@ -import { IsNull, MoreThan } from "typeorm"; -import config from "@/config/index.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { Ads, Emojis, Users } from "@/models/index.js"; -import { MAX_NOTE_TEXT_LENGTH, MAX_CAPTION_TEXT_LENGTH } from "@/const.js"; -import define from "../define.js"; - -export const meta = { - tags: ["meta"], - - requireCredential: false, - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - maintainerName: { - type: "string", - optional: false, - nullable: true, - }, - maintainerEmail: { - type: "string", - optional: false, - nullable: true, - }, - version: { - type: "string", - optional: false, - nullable: false, - example: config.version, - }, - name: { - type: "string", - optional: false, - nullable: false, - }, - uri: { - type: "string", - optional: false, - nullable: false, - format: "url", - example: "https://calckey.example.com", - }, - description: { - type: "string", - optional: false, - nullable: true, - }, - langs: { - type: "array", - optional: false, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - tosUrl: { - type: "string", - optional: false, - nullable: true, - }, - repositoryUrl: { - type: "string", - optional: false, - nullable: false, - default: "https://codeberg.org/calckey/calckey", - }, - feedbackUrl: { - type: "string", - optional: false, - nullable: false, - default: "https://codeberg.org/calckey/calckey/issues", - }, - defaultDarkTheme: { - type: "string", - optional: false, - nullable: true, - }, - defaultLightTheme: { - type: "string", - optional: false, - nullable: true, - }, - disableRegistration: { - type: "boolean", - optional: false, - nullable: false, - }, - disableLocalTimeline: { - type: "boolean", - optional: false, - nullable: false, - }, - disableRecommendedTimeline: { - type: "boolean", - optional: false, - nullable: false, - }, - disableGlobalTimeline: { - type: "boolean", - optional: false, - nullable: false, - }, - driveCapacityPerLocalUserMb: { - type: "number", - optional: false, - nullable: false, - }, - driveCapacityPerRemoteUserMb: { - type: "number", - optional: false, - nullable: false, - }, - cacheRemoteFiles: { - type: "boolean", - optional: false, - nullable: false, - }, - emailRequiredForSignup: { - type: "boolean", - optional: false, - nullable: false, - }, - enableHcaptcha: { - type: "boolean", - optional: false, - nullable: false, - }, - hcaptchaSiteKey: { - type: "string", - optional: false, - nullable: true, - }, - enableRecaptcha: { - type: "boolean", - optional: false, - nullable: false, - }, - recaptchaSiteKey: { - type: "string", - optional: false, - nullable: true, - }, - swPublickey: { - type: "string", - optional: false, - nullable: true, - }, - mascotImageUrl: { - type: "string", - optional: false, - nullable: false, - default: "/assets/ai.png", - }, - bannerUrl: { - type: "string", - optional: false, - nullable: false, - }, - errorImageUrl: { - type: "string", - optional: false, - nullable: false, - default: "https://xn--931a.moe/aiart/yubitun.png", - }, - iconUrl: { - type: "string", - optional: false, - nullable: true, - }, - maxNoteTextLength: { - type: "number", - optional: false, - nullable: false, - }, - maxCaptionTextLength: { - type: "number", - optional: false, - nullable: false, - }, - emojis: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - aliases: { - type: "array", - optional: false, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, - category: { - type: "string", - optional: false, - nullable: true, - }, - host: { - type: "string", - optional: false, - nullable: true, - description: "The local host is represented with `null`.", - }, - url: { - type: "string", - optional: false, - nullable: false, - format: "url", - }, - }, - }, - }, - ads: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - properties: { - place: { - type: "string", - optional: false, - nullable: false, - }, - url: { - type: "string", - optional: false, - nullable: false, - format: "url", - }, - imageUrl: { - type: "string", - optional: false, - nullable: false, - format: "url", - }, - }, - }, - }, - requireSetup: { - type: "boolean", - optional: false, - nullable: false, - example: false, - }, - enableEmail: { - type: "boolean", - optional: false, - nullable: false, - }, - enableTwitterIntegration: { - type: "boolean", - optional: false, - nullable: false, - }, - enableGithubIntegration: { - type: "boolean", - optional: false, - nullable: false, - }, - enableDiscordIntegration: { - type: "boolean", - optional: false, - nullable: false, - }, - enableServiceWorker: { - type: "boolean", - optional: false, - nullable: false, - }, - translatorAvailable: { - type: "boolean", - optional: false, - nullable: false, - }, - proxyAccountName: { - type: "string", - optional: false, - nullable: true, - }, - features: { - type: "object", - optional: true, - nullable: false, - properties: { - registration: { - type: "boolean", - optional: false, - nullable: false, - }, - localTimeLine: { - type: "boolean", - optional: false, - nullable: false, - }, - recommendedTimeLine: { - type: "boolean", - optional: false, - nullable: false, - }, - globalTimeLine: { - type: "boolean", - optional: false, - nullable: false, - }, - elasticsearch: { - type: "boolean", - optional: false, - nullable: false, - }, - hcaptcha: { - type: "boolean", - optional: false, - nullable: false, - }, - recaptcha: { - type: "boolean", - optional: false, - nullable: false, - }, - objectStorage: { - type: "boolean", - optional: false, - nullable: false, - }, - twitter: { - type: "boolean", - optional: false, - nullable: false, - }, - github: { - type: "boolean", - optional: false, - nullable: false, - }, - discord: { - type: "boolean", - optional: false, - nullable: false, - }, - serviceWorker: { - type: "boolean", - optional: false, - nullable: false, - }, - miauth: { - type: "boolean", - optional: true, - nullable: false, - default: true, - }, - }, - }, - secureMode: { - type: "boolean", - optional: true, - nullable: false, - default: false, - }, - privateMode: { - type: "boolean", - optional: true, - nullable: false, - default: false, - }, - defaultReaction: { - type: "string", - optional: "false", - nullable: false, - default: "⭐", - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - detail: { type: "boolean", default: true }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const instance = await fetchMeta(true); - - const emojis = await Emojis.find({ - where: { - host: IsNull(), - }, - order: { - category: "ASC", - name: "ASC", - }, - cache: { - id: "meta_emojis", - milliseconds: 3600000, // 1 hour - }, - }); - - const ads = await Ads.find({ - where: { - expiresAt: MoreThan(new Date()), - }, - }); - - const response: any = { - maintainerName: instance.maintainerName, - maintainerEmail: instance.maintainerEmail, - - version: config.version, - - name: instance.name, - uri: config.url, - description: instance.description, - langs: instance.langs, - tosUrl: instance.ToSUrl, - repositoryUrl: instance.repositoryUrl, - feedbackUrl: instance.feedbackUrl, - - secureMode: instance.secureMode, - privateMode: instance.privateMode, - - disableRegistration: instance.disableRegistration, - disableLocalTimeline: instance.disableLocalTimeline, - disableRecommendedTimeline: instance.disableRecommendedTimeline, - disableGlobalTimeline: instance.disableGlobalTimeline, - driveCapacityPerLocalUserMb: instance.localDriveCapacityMb, - driveCapacityPerRemoteUserMb: instance.remoteDriveCapacityMb, - emailRequiredForSignup: instance.emailRequiredForSignup, - enableHcaptcha: instance.enableHcaptcha, - hcaptchaSiteKey: instance.hcaptchaSiteKey, - enableRecaptcha: instance.enableRecaptcha, - recaptchaSiteKey: instance.recaptchaSiteKey, - swPublickey: instance.swPublicKey, - themeColor: instance.themeColor, - mascotImageUrl: instance.mascotImageUrl, - bannerUrl: instance.bannerUrl, - errorImageUrl: instance.errorImageUrl, - iconUrl: instance.iconUrl, - backgroundImageUrl: instance.backgroundImageUrl, - logoImageUrl: instance.logoImageUrl, - maxNoteTextLength: MAX_NOTE_TEXT_LENGTH, // 後方互換性のため - maxCaptionTextLength: MAX_CAPTION_TEXT_LENGTH, - emojis: instance.privateMode && !me ? [] : await Emojis.packMany(emojis), - defaultLightTheme: instance.defaultLightTheme, - defaultDarkTheme: instance.defaultDarkTheme, - ads: - instance.privateMode && !me - ? [] - : ads.map((ad) => ({ - id: ad.id, - url: ad.url, - place: ad.place, - ratio: ad.ratio, - imageUrl: ad.imageUrl, - })), - enableEmail: instance.enableEmail, - - enableTwitterIntegration: instance.enableTwitterIntegration, - enableGithubIntegration: instance.enableGithubIntegration, - enableDiscordIntegration: instance.enableDiscordIntegration, - - enableServiceWorker: instance.enableServiceWorker, - - translatorAvailable: instance.deeplAuthKey != null, - defaultReaction: instance.defaultReaction, - - ...(ps.detail - ? { - pinnedPages: instance.privateMode && !me ? [] : instance.pinnedPages, - pinnedClipId: - instance.privateMode && !me ? [] : instance.pinnedClipId, - cacheRemoteFiles: instance.cacheRemoteFiles, - requireSetup: - (await Users.countBy({ - host: IsNull(), - isAdmin: true, - })) === 0, - } - : {}), - }; - - if (ps.detail) { - if (!instance.privateMode || me) { - const proxyAccount = instance.proxyAccountId - ? await Users.pack(instance.proxyAccountId).catch(() => null) - : null; - response.proxyAccountName = proxyAccount ? proxyAccount.username : null; - } - - response.features = { - registration: !instance.disableRegistration, - localTimeLine: !instance.disableLocalTimeline, - recommendedTimeline: !instance.disableRecommendedTimeline, - globalTimeLine: !instance.disableGlobalTimeline, - emailRequiredForSignup: instance.emailRequiredForSignup, - elasticsearch: config.elasticsearch ? true : false, - hcaptcha: instance.enableHcaptcha, - recaptcha: instance.enableRecaptcha, - objectStorage: instance.useObjectStorage, - twitter: instance.enableTwitterIntegration, - github: instance.enableGithubIntegration, - discord: instance.enableDiscordIntegration, - serviceWorker: instance.enableServiceWorker, - miauth: true, - }; - } - - return response; -}); diff --git a/packages/backend/src/server/api/endpoints/miauth/gen-token.ts b/packages/backend/src/server/api/endpoints/miauth/gen-token.ts deleted file mode 100644 index 0525d79a7e..0000000000 --- a/packages/backend/src/server/api/endpoints/miauth/gen-token.ts +++ /dev/null @@ -1,69 +0,0 @@ -import define from "../../define.js"; -import { AccessTokens } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import { secureRndstr } from "@/misc/secure-rndstr.js"; - -export const meta = { - tags: ["auth"], - - requireCredential: true, - - secure: true, - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - token: { - type: "string", - optional: false, - nullable: false, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - session: { type: "string", nullable: true }, - name: { type: "string", nullable: true }, - description: { type: "string", nullable: true }, - iconUrl: { type: "string", nullable: true }, - permission: { - type: "array", - uniqueItems: true, - items: { - type: "string", - }, - }, - }, - required: ["session", "permission"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Generate access token - const accessToken = secureRndstr(32, true); - - const now = new Date(); - - // Insert access token doc - await AccessTokens.insert({ - id: genId(), - createdAt: now, - lastUsedAt: now, - session: ps.session, - userId: user.id, - token: accessToken, - hash: accessToken, - name: ps.name, - description: ps.description, - iconUrl: ps.iconUrl, - permission: ps.permission, - }); - - return { - token: accessToken, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/mute/create.ts b/packages/backend/src/server/api/endpoints/mute/create.ts deleted file mode 100644 index bacab9b458..0000000000 --- a/packages/backend/src/server/api/endpoints/mute/create.ts +++ /dev/null @@ -1,95 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { getUser } from "../../common/getters.js"; -import { genId } from "@/misc/gen-id.js"; -import { Mutings, NoteWatchings } from "@/models/index.js"; -import type { Muting } from "@/models/entities/muting.js"; -import { publishUserEvent } from "@/services/stream.js"; - -export const meta = { - tags: ["account"], - - requireCredential: true, - - kind: "write:mutes", - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "6fef56f3-e765-4957-88e5-c6f65329b8a5", - }, - - muteeIsYourself: { - message: "Mutee is yourself.", - code: "MUTEE_IS_YOURSELF", - id: "a4619cb2-5f23-484b-9301-94c903074e10", - }, - - alreadyMuting: { - message: "You are already muting that user.", - code: "ALREADY_MUTING", - id: "7e7359cb-160c-4956-b08f-4d1c653cd007", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - expiresAt: { - type: "integer", - nullable: true, - description: - "A Unix Epoch timestamp that must lie in the future. `null` means an indefinite mute.", - }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const muter = user; - - // 自分自身 - if (user.id === ps.userId) { - throw new ApiError(meta.errors.muteeIsYourself); - } - - // Get mutee - const mutee = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - // Check if already muting - const exist = await Mutings.findOneBy({ - muterId: muter.id, - muteeId: mutee.id, - }); - - if (exist != null) { - throw new ApiError(meta.errors.alreadyMuting); - } - - if (ps.expiresAt && ps.expiresAt <= Date.now()) { - return; - } - - // Create mute - await Mutings.insert({ - id: genId(), - createdAt: new Date(), - expiresAt: ps.expiresAt ? new Date(ps.expiresAt) : null, - muterId: muter.id, - muteeId: mutee.id, - } as Muting); - - publishUserEvent(user.id, "mute", mutee); - - NoteWatchings.delete({ - userId: muter.id, - noteUserId: mutee.id, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/mute/delete.ts b/packages/backend/src/server/api/endpoints/mute/delete.ts deleted file mode 100644 index cc67a44c26..0000000000 --- a/packages/backend/src/server/api/endpoints/mute/delete.ts +++ /dev/null @@ -1,74 +0,0 @@ -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { getUser } from "../../common/getters.js"; -import { Mutings } from "@/models/index.js"; -import { publishUserEvent } from "@/services/stream.js"; - -export const meta = { - tags: ["account"], - - requireCredential: true, - - kind: "write:mutes", - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "b851d00b-8ab1-4a56-8b1b-e24187cb48ef", - }, - - muteeIsYourself: { - message: "Mutee is yourself.", - code: "MUTEE_IS_YOURSELF", - id: "f428b029-6b39-4d48-a1d2-cc1ae6dd5cf9", - }, - - notMuting: { - message: "You are not muting that user.", - code: "NOT_MUTING", - id: "5467d020-daa9-4553-81e1-135c0c35a96d", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const muter = user; - - // Check if the mutee is yourself - if (user.id === ps.userId) { - throw new ApiError(meta.errors.muteeIsYourself); - } - - // Get mutee - const mutee = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - // Check not muting - const exist = await Mutings.findOneBy({ - muterId: muter.id, - muteeId: mutee.id, - }); - - if (exist == null) { - throw new ApiError(meta.errors.notMuting); - } - - // Delete mute - await Mutings.delete({ - id: exist.id, - }); - - publishUserEvent(user.id, "unmute", mutee); -}); diff --git a/packages/backend/src/server/api/endpoints/mute/list.ts b/packages/backend/src/server/api/endpoints/mute/list.ts deleted file mode 100644 index 7bbe29a4c8..0000000000 --- a/packages/backend/src/server/api/endpoints/mute/list.ts +++ /dev/null @@ -1,45 +0,0 @@ -import define from "../../define.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { Mutings } from "@/models/index.js"; - -export const meta = { - tags: ["account"], - - requireCredential: true, - - kind: "read:mutes", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Muting", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 30 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = makePaginationQuery( - Mutings.createQueryBuilder("muting"), - ps.sinceId, - ps.untilId, - ).andWhere("muting.muterId = :meId", { meId: me.id }); - - const mutings = await query.take(ps.limit).getMany(); - - return await Mutings.packMany(mutings, me); -}); diff --git a/packages/backend/src/server/api/endpoints/my/apps.ts b/packages/backend/src/server/api/endpoints/my/apps.ts deleted file mode 100644 index 8a097c8a04..0000000000 --- a/packages/backend/src/server/api/endpoints/my/apps.ts +++ /dev/null @@ -1,49 +0,0 @@ -import define from "../../define.js"; -import { Apps } from "@/models/index.js"; - -export const meta = { - tags: ["account", "app"], - - requireCredential: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "App", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - offset: { type: "integer", default: 0 }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = { - userId: user.id, - }; - - const apps = await Apps.find({ - where: query, - take: ps.limit, - skip: ps.offset, - }); - - return await Promise.all( - apps.map((app) => - Apps.pack(app, user, { - detail: true, - }), - ), - ); -}); diff --git a/packages/backend/src/server/api/endpoints/notes.ts b/packages/backend/src/server/api/endpoints/notes.ts deleted file mode 100644 index 9787740ab0..0000000000 --- a/packages/backend/src/server/api/endpoints/notes.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { Notes } from "@/models/index.js"; -import define from "../define.js"; -import { makePaginationQuery } from "../common/make-pagination-query.js"; - -export const meta = { - tags: ["notes"], - - requireCredentialPrivateMode: true, - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - local: { type: "boolean", default: false }, - reply: { type: "boolean" }, - renote: { type: "boolean" }, - withFiles: { type: "boolean" }, - poll: { type: "boolean" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps) => { - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - ps.sinceId, - ps.untilId, - ) - .andWhere("note.visibility = 'public'") - .andWhere("note.localOnly = FALSE") - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner"); - - if (ps.local) { - query.andWhere("note.userHost IS NULL"); - } - - if (ps.reply !== undefined) { - query.andWhere( - ps.reply ? "note.replyId IS NOT NULL" : "note.replyId IS NULL", - ); - } - - if (ps.renote !== undefined) { - query.andWhere( - ps.renote ? "note.renoteId IS NOT NULL" : "note.renoteId IS NULL", - ); - } - - if (ps.withFiles !== undefined) { - query.andWhere( - ps.withFiles ? "note.fileIds != '{}'" : "note.fileIds = '{}'", - ); - } - - if (ps.poll !== undefined) { - query.andWhere(ps.poll ? "note.hasPoll = TRUE" : "note.hasPoll = FALSE"); - } - - // TODO - //if (bot != undefined) { - // query.isBot = bot; - //} - - const notes = await query.take(ps.limit).getMany(); - - return await Notes.packMany(notes); -}); diff --git a/packages/backend/src/server/api/endpoints/notes/children.ts b/packages/backend/src/server/api/endpoints/notes/children.ts deleted file mode 100644 index 9047fcce1d..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/children.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { Brackets } from "typeorm"; -import { Notes } from "@/models/index.js"; -import define from "../../define.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { generateVisibilityQuery } from "../../common/generate-visibility-query.js"; -import { generateMutedUserQuery } from "../../common/generate-muted-user-query.js"; -import { generateBlockedUserQuery } from "../../common/generate-block-query.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, -}; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - ps.sinceId, - ps.untilId, - ) - .andWhere( - "note.id IN (SELECT id FROM note_replies(:noteId, :depth, :limit))", - { noteId: ps.noteId, depth: ps.depth, limit: ps.limit }, - ) - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner"); - - generateVisibilityQuery(query, user); - if (user) { - generateMutedUserQuery(query, user); - generateBlockedUserQuery(query, user); - } - - const notes = await query.getMany(); - - return await Notes.packMany(notes, user, { detail: false }); -}); diff --git a/packages/backend/src/server/api/endpoints/notes/clips.ts b/packages/backend/src/server/api/endpoints/notes/clips.ts deleted file mode 100644 index 34b035add2..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/clips.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { In } from "typeorm"; -import { ClipNotes, Clips } from "@/models/index.js"; -import define from "../../define.js"; -import { getNote } from "../../common/getters.js"; -import { ApiError } from "../../error.js"; - -export const meta = { - tags: ["clips", "notes"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Clip", - }, - }, - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "47db1a1c-b0af-458d-8fb4-986e4efafe1e", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const note = await getNote(ps.noteId, me).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - const clipNotes = await ClipNotes.findBy({ - noteId: note.id, - }); - - const clips = await Clips.findBy({ - id: In(clipNotes.map((x) => x.clipId)), - isPublic: true, - }); - - return await Promise.all(clips.map((x) => Clips.pack(x))); -}); diff --git a/packages/backend/src/server/api/endpoints/notes/conversation.ts b/packages/backend/src/server/api/endpoints/notes/conversation.ts deleted file mode 100644 index 2e8f5ef73b..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/conversation.ts +++ /dev/null @@ -1,81 +0,0 @@ -import type { Note } from "@/models/entities/note.js"; -import { Notes } from "@/models/index.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { getNote } from "../../common/getters.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "e1035875-9551-45ec-afa8-1ded1fcb53c8", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - offset: { type: "integer", default: 0 }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - const conversation: Note[] = []; - let i = 0; - - async function get(id: any) { - i++; - const p = await getNote(id, user).catch((e) => { - if (e.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") return null; - throw e; - }); - - if (p == null) return; - - if (i > ps.offset!) { - conversation.push(p); - } - - if (conversation.length === ps.limit) { - return; - } - - if (p.replyId) { - await get(p.replyId); - } - } - - if (note.replyId) { - await get(note.replyId); - } - - return await Notes.packMany(conversation, user); -}); diff --git a/packages/backend/src/server/api/endpoints/notes/create.ts b/packages/backend/src/server/api/endpoints/notes/create.ts deleted file mode 100644 index 41b8ab9796..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/create.ts +++ /dev/null @@ -1,308 +0,0 @@ -import { In } from "typeorm"; -import create from "@/services/note/create.js"; -import type { User } from "@/models/entities/user.js"; -import { - Users, - DriveFiles, - Notes, - Channels, - Blockings, -} from "@/models/index.js"; -import type { DriveFile } from "@/models/entities/drive-file.js"; -import type { Note } from "@/models/entities/note.js"; -import type { Channel } from "@/models/entities/channel.js"; -import { MAX_NOTE_TEXT_LENGTH } from "@/const.js"; -import { noteVisibilities } from "../../../../types.js"; -import { ApiError } from "../../error.js"; -import define from "../../define.js"; -import { HOUR } from "@/const.js"; -import { getNote } from "../../common/getters.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: true, - - limit: { - duration: HOUR, - max: 300, - }, - - kind: "write:notes", - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - createdNote: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, - }, - - errors: { - noSuchRenoteTarget: { - message: "No such renote target.", - code: "NO_SUCH_RENOTE_TARGET", - id: "b5c90186-4ab0-49c8-9bba-a1f76c282ba4", - }, - - cannotReRenote: { - message: "You can not Renote a pure Renote.", - code: "CANNOT_RENOTE_TO_A_PURE_RENOTE", - id: "fd4cc33e-2a37-48dd-99cc-9b806eb2031a", - }, - - noSuchReplyTarget: { - message: "No such reply target.", - code: "NO_SUCH_REPLY_TARGET", - id: "749ee0f6-d3da-459a-bf02-282e2da4292c", - }, - - cannotReplyToPureRenote: { - message: "You can not reply to a pure Renote.", - code: "CANNOT_REPLY_TO_A_PURE_RENOTE", - id: "3ac74a84-8fd5-4bb0-870f-01804f82ce15", - }, - - cannotCreateAlreadyExpiredPoll: { - message: "Poll is already expired.", - code: "CANNOT_CREATE_ALREADY_EXPIRED_POLL", - id: "04da457d-b083-4055-9082-955525eda5a5", - }, - - noSuchChannel: { - message: "No such channel.", - code: "NO_SUCH_CHANNEL", - id: "b1653923-5453-4edc-b786-7c4f39bb0bbb", - }, - - youHaveBeenBlocked: { - message: "You have been blocked by this user.", - code: "YOU_HAVE_BEEN_BLOCKED", - id: "b390d7e1-8a5e-46ed-b625-06271cafd3d3", - }, - - accountLocked: { - message: "You migrated. Your account is now locked.", - code: "ACCOUNT_LOCKED", - id: "d390d7e1-8a5e-46ed-b625-06271cafd3d3", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - visibility: { type: "string", enum: noteVisibilities, default: "public" }, - visibleUserIds: { - type: "array", - uniqueItems: true, - items: { - type: "string", - format: "misskey:id", - }, - }, - text: { type: "string", maxLength: MAX_NOTE_TEXT_LENGTH, nullable: true }, - cw: { type: "string", nullable: true, maxLength: 100 }, - localOnly: { type: "boolean", default: false }, - noExtractMentions: { type: "boolean", default: false }, - noExtractHashtags: { type: "boolean", default: false }, - noExtractEmojis: { type: "boolean", default: false }, - fileIds: { - type: "array", - uniqueItems: true, - minItems: 1, - maxItems: 16, - items: { type: "string", format: "misskey:id" }, - }, - mediaIds: { - deprecated: true, - description: - "Use `fileIds` instead. If both are specified, this property is discarded.", - type: "array", - uniqueItems: true, - minItems: 1, - maxItems: 16, - items: { type: "string", format: "misskey:id" }, - }, - replyId: { type: "string", format: "misskey:id", nullable: true }, - renoteId: { type: "string", format: "misskey:id", nullable: true }, - channelId: { type: "string", format: "misskey:id", nullable: true }, - poll: { - type: "object", - nullable: true, - properties: { - choices: { - type: "array", - uniqueItems: true, - minItems: 2, - maxItems: 10, - items: { type: "string", minLength: 1, maxLength: 50 }, - }, - multiple: { type: "boolean", default: false }, - expiresAt: { type: "integer", nullable: true }, - expiredAfter: { type: "integer", nullable: true, minimum: 1 }, - }, - required: ["choices"], - }, - }, - anyOf: [ - { - // (re)note with text, files and poll are optional - properties: { - text: { - type: "string", - minLength: 1, - maxLength: MAX_NOTE_TEXT_LENGTH, - nullable: false, - }, - }, - required: ["text"], - }, - { - // (re)note with files, text and poll are optional - required: ["fileIds"], - }, - { - // (re)note with files, text and poll are optional - required: ["mediaIds"], - }, - { - // (re)note with poll, text and files are optional - properties: { - poll: { type: "object", nullable: false }, - }, - required: ["poll"], - }, - { - // pure renote - required: ["renoteId"], - }, - ], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - if (user.movedToUri != null) throw new ApiError(meta.errors.accountLocked); - let visibleUsers: User[] = []; - if (ps.visibleUserIds) { - visibleUsers = await Users.findBy({ - id: In(ps.visibleUserIds), - }); - } - - let files: DriveFile[] = []; - const fileIds = - ps.fileIds != null ? ps.fileIds : ps.mediaIds != null ? ps.mediaIds : null; - if (fileIds != null) { - files = await DriveFiles.createQueryBuilder("file") - .where("file.userId = :userId AND file.id IN (:...fileIds)", { - userId: user.id, - fileIds, - }) - .orderBy('array_position(ARRAY[:...fileIds], "id"::text)') - .setParameters({ fileIds }) - .getMany(); - } - - let renote: Note | null = null; - if (ps.renoteId != null) { - // Fetch renote to note - renote = await getNote(ps.renoteId, user).catch((e) => { - if (e.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchRenoteTarget); - throw e; - }); - - if (renote.renoteId && !renote.text && !renote.fileIds && !renote.hasPoll) { - throw new ApiError(meta.errors.cannotReRenote); - } - - // Check blocking - if (renote.userId !== user.id) { - const block = await Blockings.findOneBy({ - blockerId: renote.userId, - blockeeId: user.id, - }); - if (block) { - throw new ApiError(meta.errors.youHaveBeenBlocked); - } - } - } - - let reply: Note | null = null; - if (ps.replyId != null) { - // Fetch reply - reply = await getNote(ps.replyId, user).catch((e) => { - if (e.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchReplyTarget); - throw e; - }); - - if (reply.renoteId && !reply.text && !reply.fileIds && !reply.hasPoll) { - throw new ApiError(meta.errors.cannotReplyToPureRenote); - } - - // Check blocking - if (reply.userId !== user.id) { - const block = await Blockings.findOneBy({ - blockerId: reply.userId, - blockeeId: user.id, - }); - if (block) { - throw new ApiError(meta.errors.youHaveBeenBlocked); - } - } - } - - if (ps.poll) { - if (typeof ps.poll.expiresAt === "number") { - if (ps.poll.expiresAt < Date.now()) { - throw new ApiError(meta.errors.cannotCreateAlreadyExpiredPoll); - } - } else if (typeof ps.poll.expiredAfter === "number") { - ps.poll.expiresAt = Date.now() + ps.poll.expiredAfter; - } - } - - let channel: Channel | null = null; - if (ps.channelId != null) { - channel = await Channels.findOneBy({ id: ps.channelId }); - - if (channel == null) { - throw new ApiError(meta.errors.noSuchChannel); - } - } - - // Create a post - const note = await create(user, { - createdAt: new Date(), - files: files, - poll: ps.poll - ? { - choices: ps.poll.choices, - multiple: ps.poll.multiple, - expiresAt: ps.poll.expiresAt ? new Date(ps.poll.expiresAt) : null, - } - : undefined, - text: ps.text || undefined, - reply, - renote, - cw: ps.cw, - localOnly: ps.localOnly, - visibility: ps.visibility, - visibleUsers, - channel, - apMentions: ps.noExtractMentions ? [] : undefined, - apHashtags: ps.noExtractHashtags ? [] : undefined, - apEmojis: ps.noExtractEmojis ? [] : undefined, - }); - - return { - createdNote: await Notes.pack(note, user), - }; -}); diff --git a/packages/backend/src/server/api/endpoints/notes/delete.ts b/packages/backend/src/server/api/endpoints/notes/delete.ts deleted file mode 100644 index 5fc79db7d1..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/delete.ts +++ /dev/null @@ -1,57 +0,0 @@ -import deleteNote from "@/services/note/delete.js"; -import { Users } from "@/models/index.js"; -import define from "../../define.js"; -import { getNote } from "../../common/getters.js"; -import { ApiError } from "../../error.js"; -import { SECOND, HOUR } from "@/const.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: true, - - kind: "write:notes", - - limit: { - duration: HOUR, - max: 300, - minInterval: SECOND, - }, - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "490be23f-8c1f-4796-819f-94cb4f9d1630", - }, - - accessDenied: { - message: "Access denied.", - code: "ACCESS_DENIED", - id: "fe8d7103-0ea8-4ec3-814d-f8b401dc69e9", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - if (!(user.isAdmin || user.isModerator) && note.userId !== user.id) { - throw new ApiError(meta.errors.accessDenied); - } - - // この操作を行うのが投稿者とは限らない(例えばモデレーター)ため - await deleteNote(await Users.findOneByOrFail({ id: note.userId }), note); -}); diff --git a/packages/backend/src/server/api/endpoints/notes/favorites/create.ts b/packages/backend/src/server/api/endpoints/notes/favorites/create.ts deleted file mode 100644 index 835594f03a..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/favorites/create.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { NoteFavorites } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { getNote } from "../../../common/getters.js"; - -export const meta = { - tags: ["notes", "favorites"], - - requireCredential: true, - - kind: "write:favorites", - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "6dd26674-e060-4816-909a-45ba3f4da458", - }, - - alreadyFavorited: { - message: "The note has already been marked as a favorite.", - code: "ALREADY_FAVORITED", - id: "a402c12b-34dd-41d2-97d8-4d2ffd96a1a6", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Get favoritee - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - // if already favorited - const exist = await NoteFavorites.findOneBy({ - noteId: note.id, - userId: user.id, - }); - - if (exist != null) { - throw new ApiError(meta.errors.alreadyFavorited); - } - - // Create favorite - await NoteFavorites.insert({ - id: genId(), - createdAt: new Date(), - noteId: note.id, - userId: user.id, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/notes/favorites/delete.ts b/packages/backend/src/server/api/endpoints/notes/favorites/delete.ts deleted file mode 100644 index 9a09767482..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/favorites/delete.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { NoteFavorites } from "@/models/index.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { getNote } from "../../../common/getters.js"; - -export const meta = { - tags: ["notes", "favorites"], - - requireCredential: true, - - kind: "write:favorites", - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "80848a2c-398f-4343-baa9-df1d57696c56", - }, - - notFavorited: { - message: "You have not marked that note a favorite.", - code: "NOT_FAVORITED", - id: "b625fc69-635e-45e9-86f4-dbefbef35af5", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Get favoritee - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - // if already favorited - const exist = await NoteFavorites.findOneBy({ - noteId: note.id, - userId: user.id, - }); - - if (exist == null) { - throw new ApiError(meta.errors.notFavorited); - } - - // Delete favorite - await NoteFavorites.delete(exist.id); -}); diff --git a/packages/backend/src/server/api/endpoints/notes/featured.ts b/packages/backend/src/server/api/endpoints/notes/featured.ts deleted file mode 100644 index 47c1e13812..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/featured.ts +++ /dev/null @@ -1,82 +0,0 @@ -import { Notes } from "@/models/index.js"; -import define from "../../define.js"; -import { generateMutedUserQuery } from "../../common/generate-muted-user-query.js"; -import { generateBlockedUserQuery } from "../../common/generate-block-query.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - offset: { type: "integer", default: 0 }, - origin: { - type: "string", - enum: ["combined", "local", "remote"], - default: "local", - }, - days: { type: "integer", minimum: 1, maximum: 365, default: 3 }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const max = 30; - const day = 1000 * 60 * 60 * 24 * ps.days; - - const query = Notes.createQueryBuilder("note") - .addSelect("note.score") - .andWhere("note.score > 0") - .andWhere("note.createdAt > :date", { date: new Date(Date.now() - day) }) - .andWhere("note.visibility = 'public'") - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner"); - - switch (ps.origin) { - case "local": - query.andWhere("note.userHost IS NULL"); - break; - case "remote": - query.andWhere("note.userHost IS NOT NULL"); - break; - } - - if (user) generateMutedUserQuery(query, user); - if (user) generateBlockedUserQuery(query, user); - - let notes = await query.orderBy("note.score", "DESC").take(max).getMany(); - - notes.sort( - (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(), - ); - - notes = notes.slice(ps.offset, ps.offset + ps.limit); - - return await Notes.packMany(notes, user); -}); diff --git a/packages/backend/src/server/api/endpoints/notes/global-timeline.ts b/packages/backend/src/server/api/endpoints/notes/global-timeline.ts deleted file mode 100644 index 077a1ad5e1..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/global-timeline.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { Notes } from "@/models/index.js"; -import { activeUsersChart } from "@/services/chart/index.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { generateMutedUserQuery } from "../../common/generate-muted-user-query.js"; -import { generateRepliesQuery } from "../../common/generate-replies-query.js"; -import { generateMutedNoteQuery } from "../../common/generate-muted-note-query.js"; -import { generateBlockedUserQuery } from "../../common/generate-block-query.js"; -import { generateMutedUserRenotesQueryForNotes } from "../../common/generated-muted-renote-query.js"; - -export const meta = { - tags: ["notes"], - - requireCredentialPrivateMode: true, - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, - - errors: { - gtlDisabled: { - message: "Global timeline has been disabled.", - code: "GTL_DISABLED", - id: "0332fc13-6ab2-4427-ae80-a9fadffd1a6b", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - withFiles: { - type: "boolean", - default: false, - description: "Only show notes that have attached files.", - }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - sinceDate: { type: "integer" }, - untilDate: { type: "integer" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const m = await fetchMeta(); - if (m.disableGlobalTimeline) { - if (user == null || !(user.isAdmin || user.isModerator)) { - throw new ApiError(meta.errors.gtlDisabled); - } - } - - //#region Construct query - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - ps.sinceId, - ps.untilId, - ps.sinceDate, - ps.untilDate, - ) - .andWhere("note.visibility = 'public'") - .andWhere("note.channelId IS NULL") - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner"); - - generateRepliesQuery(query, user); - if (user) { - generateMutedUserQuery(query, user); - generateMutedNoteQuery(query, user); - generateBlockedUserQuery(query, user); - generateMutedUserRenotesQueryForNotes(query, user); - } - - if (ps.withFiles) { - query.andWhere("note.fileIds != '{}'"); - } - //#endregion - - process.nextTick(() => { - if (user) { - activeUsersChart.read(user); - } - }); - - // We fetch more than requested because some may be filtered out, and if there's less than - // requested, the pagination stops. - const found = []; - const take = Math.floor(ps.limit * 1.5); - let skip = 0; - while (found.length < ps.limit) { - const notes = await query.take(take).skip(skip).getMany(); - found.push(...(await Notes.packMany(notes, user))); - skip += take; - if (notes.length < take) break; - } - - if (found.length > ps.limit) { - found.length = ps.limit; - } - - return found; -}); diff --git a/packages/backend/src/server/api/endpoints/notes/hybrid-timeline.ts b/packages/backend/src/server/api/endpoints/notes/hybrid-timeline.ts deleted file mode 100644 index 3c171278b4..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/hybrid-timeline.ts +++ /dev/null @@ -1,177 +0,0 @@ -import { Brackets } from "typeorm"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { Followings, Notes } from "@/models/index.js"; -import { activeUsersChart } from "@/services/chart/index.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { generateVisibilityQuery } from "../../common/generate-visibility-query.js"; -import { generateMutedUserQuery } from "../../common/generate-muted-user-query.js"; -import { generateRepliesQuery } from "../../common/generate-replies-query.js"; -import { generateMutedNoteQuery } from "../../common/generate-muted-note-query.js"; -import { generateChannelQuery } from "../../common/generate-channel-query.js"; -import { generateBlockedUserQuery } from "../../common/generate-block-query.js"; -import { generateMutedUserRenotesQueryForNotes } from "../../common/generated-muted-renote-query.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, - - errors: { - stlDisabled: { - message: "Hybrid timeline has been disabled.", - code: "STL_DISABLED", - id: "620763f4-f621-4533-ab33-0577a1a3c342", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - sinceDate: { type: "integer" }, - untilDate: { type: "integer" }, - includeMyRenotes: { type: "boolean", default: true }, - includeRenotedMyNotes: { type: "boolean", default: true }, - includeLocalRenotes: { type: "boolean", default: true }, - withFiles: { - type: "boolean", - default: false, - description: "Only show notes that have attached files.", - }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const m = await fetchMeta(); - if (m.disableLocalTimeline && !user.isAdmin && !user.isModerator) { - throw new ApiError(meta.errors.stlDisabled); - } - - //#region Construct query - const followingQuery = Followings.createQueryBuilder("following") - .select("following.followeeId") - .where("following.followerId = :followerId", { followerId: user.id }); - - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - ps.sinceId, - ps.untilId, - ps.sinceDate, - ps.untilDate, - ) - .andWhere( - new Brackets((qb) => { - qb.where( - `((note.userId IN (${followingQuery.getQuery()})) OR (note.userId = :meId))`, - { meId: user.id }, - ).orWhere("(note.visibility = 'public') AND (note.userHost IS NULL)"); - }), - ) - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner") - .setParameters(followingQuery.getParameters()); - - generateChannelQuery(query, user); - generateRepliesQuery(query, user); - generateVisibilityQuery(query, user); - generateMutedUserQuery(query, user); - generateMutedNoteQuery(query, user); - generateBlockedUserQuery(query, user); - generateMutedUserRenotesQueryForNotes(query, user); - - if (ps.includeMyRenotes === false) { - query.andWhere( - new Brackets((qb) => { - qb.orWhere("note.userId != :meId", { meId: user.id }); - qb.orWhere("note.renoteId IS NULL"); - qb.orWhere("note.text IS NOT NULL"); - qb.orWhere("note.fileIds != '{}'"); - qb.orWhere( - '0 < (SELECT COUNT(*) FROM poll WHERE poll."noteId" = note.id)', - ); - }), - ); - } - - if (ps.includeRenotedMyNotes === false) { - query.andWhere( - new Brackets((qb) => { - qb.orWhere("note.renoteUserId != :meId", { meId: user.id }); - qb.orWhere("note.renoteId IS NULL"); - qb.orWhere("note.text IS NOT NULL"); - qb.orWhere("note.fileIds != '{}'"); - qb.orWhere( - '0 < (SELECT COUNT(*) FROM poll WHERE poll."noteId" = note.id)', - ); - }), - ); - } - - if (ps.includeLocalRenotes === false) { - query.andWhere( - new Brackets((qb) => { - qb.orWhere("note.renoteUserHost IS NOT NULL"); - qb.orWhere("note.renoteId IS NULL"); - qb.orWhere("note.text IS NOT NULL"); - qb.orWhere("note.fileIds != '{}'"); - qb.orWhere( - '0 < (SELECT COUNT(*) FROM poll WHERE poll."noteId" = note.id)', - ); - }), - ); - } - - if (ps.withFiles) { - query.andWhere("note.fileIds != '{}'"); - } - //#endregion - - process.nextTick(() => { - activeUsersChart.read(user); - }); - - // We fetch more than requested because some may be filtered out, and if there's less than - // requested, the pagination stops. - const found = []; - const take = Math.floor(ps.limit * 1.5); - let skip = 0; - while (found.length < ps.limit) { - const notes = await query.take(take).skip(skip).getMany(); - found.push(...(await Notes.packMany(notes, user))); - skip += take; - if (notes.length < take) break; - } - - if (found.length > ps.limit) { - found.length = ps.limit; - } - - return found; -}); diff --git a/packages/backend/src/server/api/endpoints/notes/local-timeline.ts b/packages/backend/src/server/api/endpoints/notes/local-timeline.ts deleted file mode 100644 index cec371c8dc..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/local-timeline.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { Brackets } from "typeorm"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { Notes, Users } from "@/models/index.js"; -import { activeUsersChart } from "@/services/chart/index.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { generateMutedUserQuery } from "../../common/generate-muted-user-query.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { generateVisibilityQuery } from "../../common/generate-visibility-query.js"; -import { generateRepliesQuery } from "../../common/generate-replies-query.js"; -import { generateMutedNoteQuery } from "../../common/generate-muted-note-query.js"; -import { generateChannelQuery } from "../../common/generate-channel-query.js"; -import { generateBlockedUserQuery } from "../../common/generate-block-query.js"; -import { generateMutedUserRenotesQueryForNotes } from "../../common/generated-muted-renote-query.js"; - -export const meta = { - tags: ["notes"], - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, - - errors: { - ltlDisabled: { - message: "Local timeline has been disabled.", - code: "LTL_DISABLED", - id: "45a6eb02-7695-4393-b023-dd3be9aaaefd", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - withFiles: { - type: "boolean", - default: false, - description: "Only show notes that have attached files.", - }, - fileType: { - type: "array", - items: { - type: "string", - }, - }, - excludeNsfw: { type: "boolean", default: false }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - sinceDate: { type: "integer" }, - untilDate: { type: "integer" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const m = await fetchMeta(); - if (m.disableLocalTimeline) { - if (user == null || !(user.isAdmin || user.isModerator)) { - throw new ApiError(meta.errors.ltlDisabled); - } - } - - //#region Construct query - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - ps.sinceId, - ps.untilId, - ps.sinceDate, - ps.untilDate, - ) - .andWhere("(note.visibility = 'public') AND (note.userHost IS NULL)") - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner"); - - generateChannelQuery(query, user); - generateRepliesQuery(query, user); - generateVisibilityQuery(query, user); - if (user) generateMutedUserQuery(query, user); - if (user) generateMutedNoteQuery(query, user); - if (user) generateBlockedUserQuery(query, user); - if (user) generateMutedUserRenotesQueryForNotes(query, user); - - if (ps.withFiles) { - query.andWhere("note.fileIds != '{}'"); - } - - if (ps.fileType != null) { - query.andWhere("note.fileIds != '{}'"); - query.andWhere( - new Brackets((qb) => { - for (const type of ps.fileType!) { - const i = ps.fileType!.indexOf(type); - qb.orWhere(`:type${i} = ANY(note.attachedFileTypes)`, { - [`type${i}`]: type, - }); - } - }), - ); - - if (ps.excludeNsfw) { - query.andWhere("note.cw IS NULL"); - query.andWhere( - '0 = (SELECT COUNT(*) FROM drive_file df WHERE df.id = ANY(note."fileIds") AND df."isSensitive" = TRUE)', - ); - } - } - //#endregion - - process.nextTick(() => { - if (user) { - activeUsersChart.read(user); - } - }); - - // We fetch more than requested because some may be filtered out, and if there's less than - // requested, the pagination stops. - const found = []; - const take = Math.floor(ps.limit * 1.5); - let skip = 0; - while (found.length < ps.limit) { - const notes = await query.take(take).skip(skip).getMany(); - found.push(...(await Notes.packMany(notes, user))); - skip += take; - if (notes.length < take) break; - } - - if (found.length > ps.limit) { - found.length = ps.limit; - } - - return found; -}); diff --git a/packages/backend/src/server/api/endpoints/notes/mentions.ts b/packages/backend/src/server/api/endpoints/notes/mentions.ts deleted file mode 100644 index 68688b504c..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/mentions.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { Brackets } from "typeorm"; -import read from "@/services/note/read.js"; -import { Notes, Followings } from "@/models/index.js"; -import define from "../../define.js"; -import { generateVisibilityQuery } from "../../common/generate-visibility-query.js"; -import { generateMutedUserQuery } from "../../common/generate-muted-user-query.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { generateBlockedUserQuery } from "../../common/generate-block-query.js"; -import { generateMutedNoteThreadQuery } from "../../common/generate-muted-note-thread-query.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - following: { type: "boolean", default: false }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - visibility: { type: "string" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const followingQuery = Followings.createQueryBuilder("following") - .select("following.followeeId") - .where("following.followerId = :followerId", { followerId: user.id }); - - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - ps.sinceId, - ps.untilId, - ) - .andWhere( - new Brackets((qb) => { - qb.where(`'{"${user.id}"}' <@ note.mentions`).orWhere( - `'{"${user.id}"}' <@ note.visibleUserIds`, - ); - }), - ) - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner"); - - generateVisibilityQuery(query, user); - generateMutedUserQuery(query, user); - generateMutedNoteThreadQuery(query, user); - generateBlockedUserQuery(query, user); - - if (ps.visibility) { - query.andWhere("note.visibility = :visibility", { - visibility: ps.visibility, - }); - } - - if (ps.following) { - query.andWhere( - `((note.userId IN (${followingQuery.getQuery()})) OR (note.userId = :meId))`, - { meId: user.id }, - ); - query.setParameters(followingQuery.getParameters()); - } - - // We fetch more than requested because some may be filtered out, and if there's less than - // requested, the pagination stops. - const found = []; - const take = Math.floor(ps.limit * 1.5); - let skip = 0; - while (found.length < ps.limit) { - const notes = await query.take(take).skip(skip).getMany(); - found.push(...(await Notes.packMany(notes, user))); - skip += take; - if (notes.length < take) break; - } - - if (found.length > ps.limit) { - found.length = ps.limit; - } - - read(user.id, found); - - return found; -}); diff --git a/packages/backend/src/server/api/endpoints/notes/polls/recommendation.ts b/packages/backend/src/server/api/endpoints/notes/polls/recommendation.ts deleted file mode 100644 index fcd24db992..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/polls/recommendation.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { Brackets, In } from "typeorm"; -import { Polls, Mutings, Notes, PollVotes } from "@/models/index.js"; -import define from "../../../define.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - offset: { type: "integer", default: 0 }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = Polls.createQueryBuilder("poll") - .where("poll.userHost IS NULL") - .andWhere("poll.userId != :meId", { meId: user.id }) - .andWhere("poll.noteVisibility = 'public'") - .andWhere( - new Brackets((qb) => { - qb.where("poll.expiresAt IS NULL").orWhere("poll.expiresAt > :now", { - now: new Date(), - }); - }), - ); - - //#region exclude arleady voted polls - const votedQuery = PollVotes.createQueryBuilder("vote") - .select("vote.noteId") - .where("vote.userId = :meId", { meId: user.id }); - - query.andWhere(`poll.noteId NOT IN (${votedQuery.getQuery()})`); - - query.setParameters(votedQuery.getParameters()); - //#endregion - - //#region mute - const mutingQuery = Mutings.createQueryBuilder("muting") - .select("muting.muteeId") - .where("muting.muterId = :muterId", { muterId: user.id }); - - query.andWhere(`poll.userId NOT IN (${mutingQuery.getQuery()})`); - - query.setParameters(mutingQuery.getParameters()); - //#endregion - - const polls = await query - .orderBy("poll.noteId", "DESC") - .take(ps.limit) - .skip(ps.offset) - .getMany(); - - if (polls.length === 0) return []; - - const notes = await Notes.find({ - where: { - id: In(polls.map((poll) => poll.noteId)), - }, - order: { - createdAt: "DESC", - }, - }); - - return await Notes.packMany(notes, user, { - detail: true, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/notes/polls/vote.ts b/packages/backend/src/server/api/endpoints/notes/polls/vote.ts deleted file mode 100644 index 0558aa1b8f..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/polls/vote.ts +++ /dev/null @@ -1,184 +0,0 @@ -import { Not } from "typeorm"; -import { publishNoteStream } from "@/services/stream.js"; -import { createNotification } from "@/services/create-notification.js"; -import { deliver } from "@/queue/index.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import renderVote from "@/remote/activitypub/renderer/vote.js"; -import { deliverQuestionUpdate } from "@/services/note/polls/update.js"; -import { - PollVotes, - NoteWatchings, - Users, - Polls, - Blockings, -} from "@/models/index.js"; -import type { IRemoteUser } from "@/models/entities/user.js"; -import { genId } from "@/misc/gen-id.js"; -import { getNote } from "../../../common/getters.js"; -import { ApiError } from "../../../error.js"; -import define from "../../../define.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: true, - - kind: "write:votes", - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "ecafbd2e-c283-4d6d-aecb-1a0a33b75396", - }, - - noPoll: { - message: "The note does not attach a poll.", - code: "NO_POLL", - id: "5f979967-52d9-4314-a911-1c673727f92f", - }, - - invalidChoice: { - message: "Choice ID is invalid.", - code: "INVALID_CHOICE", - id: "e0cc9a04-f2e8-41e4-a5f1-4127293260cc", - }, - - alreadyVoted: { - message: "You have already voted.", - code: "ALREADY_VOTED", - id: "0963fc77-efac-419b-9424-b391608dc6d8", - }, - - alreadyExpired: { - message: "The poll is already expired.", - code: "ALREADY_EXPIRED", - id: "1022a357-b085-4054-9083-8f8de358337e", - }, - - youHaveBeenBlocked: { - message: - "You cannot vote this poll because you have been blocked by this user.", - code: "YOU_HAVE_BEEN_BLOCKED", - id: "85a5377e-b1e9-4617-b0b9-5bea73331e49", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - choice: { type: "integer" }, - }, - required: ["noteId", "choice"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const createdAt = new Date(); - - // Get votee - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - if (!note.hasPoll) { - throw new ApiError(meta.errors.noPoll); - } - - // Check blocking - if (note.userId !== user.id) { - const block = await Blockings.findOneBy({ - blockerId: note.userId, - blockeeId: user.id, - }); - if (block) { - throw new ApiError(meta.errors.youHaveBeenBlocked); - } - } - - const poll = await Polls.findOneByOrFail({ noteId: note.id }); - - if (poll.expiresAt && poll.expiresAt < createdAt) { - throw new ApiError(meta.errors.alreadyExpired); - } - - if (poll.choices[ps.choice] == null) { - throw new ApiError(meta.errors.invalidChoice); - } - - // if already voted - const exist = await PollVotes.findBy({ - noteId: note.id, - userId: user.id, - }); - - if (exist.length) { - if (poll.multiple) { - if (exist.some((x) => x.choice === ps.choice)) { - throw new ApiError(meta.errors.alreadyVoted); - } - } else { - throw new ApiError(meta.errors.alreadyVoted); - } - } - - // Create vote - const vote = await PollVotes.insert({ - id: genId(), - createdAt, - noteId: note.id, - userId: user.id, - choice: ps.choice, - }).then((x) => PollVotes.findOneByOrFail(x.identifiers[0])); - - // Increment votes count - const index = ps.choice + 1; // In SQL, array index is 1 based - await Polls.query( - `UPDATE poll SET votes[${index}] = votes[${index}] + 1 WHERE "noteId" = '${poll.noteId}'`, - ); - - publishNoteStream(note.id, "pollVoted", { - choice: ps.choice, - userId: user.id, - }); - - // Notify - createNotification(note.userId, "pollVote", { - notifierId: user.id, - noteId: note.id, - choice: ps.choice, - }); - - // Fetch watchers - NoteWatchings.findBy({ - noteId: note.id, - userId: Not(user.id), - }).then((watchers) => { - for (const watcher of watchers) { - createNotification(watcher.userId, "pollVote", { - notifierId: user.id, - noteId: note.id, - choice: ps.choice, - }); - } - }); - - // リモート投票の場合リプライ送信 - if (note.userHost != null) { - const pollOwner = (await Users.findOneByOrFail({ - id: note.userId, - })) as IRemoteUser; - - deliver( - user, - renderActivity(await renderVote(user, vote, note, poll, pollOwner)), - pollOwner.inbox, - ); - } - - // リモートフォロワーにUpdate配信 - deliverQuestionUpdate(note.id); -}); diff --git a/packages/backend/src/server/api/endpoints/notes/reactions.ts b/packages/backend/src/server/api/endpoints/notes/reactions.ts deleted file mode 100644 index 3c8af119ab..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/reactions.ts +++ /dev/null @@ -1,85 +0,0 @@ -import type { FindOptionsWhere } from "typeorm"; -import { DeepPartial } from "typeorm"; -import { NoteReactions } from "@/models/index.js"; -import type { NoteReaction } from "@/models/entities/note-reaction.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { getNote } from "../../common/getters.js"; - -export const meta = { - tags: ["notes", "reactions"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - allowGet: true, - cacheSec: 60, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "NoteReaction", - }, - }, - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "263fff3d-d0e1-4af4-bea7-8408059b451a", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - type: { type: "string", nullable: true }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - offset: { type: "integer", default: 0 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // check note visibility - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - const query = { - noteId: ps.noteId, - } as FindOptionsWhere<NoteReaction>; - - if (ps.type) { - // ローカルリアクションはホスト名が . とされているが - // DB 上ではそうではないので、必要に応じて変換 - const suffix = "@.:"; - const type = ps.type.endsWith(suffix) - ? `${ps.type.slice(0, ps.type.length - suffix.length)}:` - : ps.type; - query.reaction = type; - } - - const reactions = await NoteReactions.find({ - where: query, - take: ps.limit, - skip: ps.offset, - order: { - id: -1, - }, - relations: ["user", "user.avatar", "user.banner", "note"], - }); - - return await NoteReactions.packMany(reactions, user); -}); diff --git a/packages/backend/src/server/api/endpoints/notes/reactions/create.ts b/packages/backend/src/server/api/endpoints/notes/reactions/create.ts deleted file mode 100644 index 2c8671070f..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/reactions/create.ts +++ /dev/null @@ -1,64 +0,0 @@ -import createReaction from "@/services/note/reaction/create.js"; -import define from "../../../define.js"; -import { getNote } from "../../../common/getters.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["reactions", "notes"], - - requireCredential: true, - - kind: "write:reactions", - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "033d0620-5bfe-4027-965d-980b0c85a3ea", - }, - - alreadyReacted: { - message: "You are already reacting to that note.", - code: "ALREADY_REACTED", - id: "71efcf98-86d6-4e2b-b2ad-9d032369366b", - }, - - youHaveBeenBlocked: { - message: - "You cannot react this note because you have been blocked by this user.", - code: "YOU_HAVE_BEEN_BLOCKED", - id: "20ef5475-9f38-4e4c-bd33-de6d979498ec", - }, - accountLocked: { - message: "You migrated. Your account is now locked.", - code: "ACCOUNT_LOCKED", - id: "d390d7e1-8a5e-46ed-b625-06271cafd3d3", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - reaction: { type: "string" }, - }, - required: ["noteId", "reaction"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - if (user.movedToUri != null) throw new ApiError(meta.errors.accountLocked); - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - await createReaction(user, note, ps.reaction).catch((e) => { - if (e.id === "51c42bb4-931a-456b-bff7-e5a8a70dd298") - throw new ApiError(meta.errors.alreadyReacted); - if (e.id === "e70412a4-7197-4726-8e74-f3e0deb92aa7") - throw new ApiError(meta.errors.youHaveBeenBlocked); - throw e; - }); - return; -}); diff --git a/packages/backend/src/server/api/endpoints/notes/reactions/delete.ts b/packages/backend/src/server/api/endpoints/notes/reactions/delete.ts deleted file mode 100644 index 59096c4c88..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/reactions/delete.ts +++ /dev/null @@ -1,54 +0,0 @@ -import deleteReaction from "@/services/note/reaction/delete.js"; -import define from "../../../define.js"; -import { getNote } from "../../../common/getters.js"; -import { ApiError } from "../../../error.js"; -import { SECOND, HOUR } from "@/const.js"; - -export const meta = { - tags: ["reactions", "notes"], - - requireCredential: true, - - kind: "write:reactions", - - limit: { - duration: HOUR, - max: 60, - minInterval: 3 * SECOND, - }, - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "764d9fce-f9f2-4a0e-92b1-6ceac9a7ad37", - }, - - notReacted: { - message: "You are not reacting to that note.", - code: "NOT_REACTED", - id: "92f4426d-4196-4125-aa5b-02943e2ec8fc", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - await deleteReaction(user, note).catch((e) => { - if (e.id === "60527ec9-b4cb-4a88-a6bd-32d3ad26817d") - throw new ApiError(meta.errors.notReacted); - throw e; - }); -}); diff --git a/packages/backend/src/server/api/endpoints/notes/recommended-timeline.ts b/packages/backend/src/server/api/endpoints/notes/recommended-timeline.ts deleted file mode 100644 index 56847b1dd2..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/recommended-timeline.ts +++ /dev/null @@ -1,154 +0,0 @@ -import { Brackets } from "typeorm"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { Notes } from "@/models/index.js"; -import { activeUsersChart } from "@/services/chart/index.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { generateMutedUserQuery } from "../../common/generate-muted-user-query.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { generateVisibilityQuery } from "../../common/generate-visibility-query.js"; -import { generateRepliesQuery } from "../../common/generate-replies-query.js"; -import { generateMutedNoteQuery } from "../../common/generate-muted-note-query.js"; -import { generateChannelQuery } from "../../common/generate-channel-query.js"; -import { generateBlockedUserQuery } from "../../common/generate-block-query.js"; -import { generateMutedUserRenotesQueryForNotes } from "../../common/generated-muted-renote-query.js"; - -export const meta = { - tags: ["notes"], - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, - - errors: { - rtlDisabled: { - message: "Recommended timeline has been disabled.", - code: "RTL_DISABLED", - id: "45a6eb02-7695-4393-b023-dd3be9aaaefe", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - withFiles: { - type: "boolean", - default: false, - description: "Only show notes that have attached files.", - }, - fileType: { - type: "array", - items: { - type: "string", - }, - }, - excludeNsfw: { type: "boolean", default: false }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - sinceDate: { type: "integer" }, - untilDate: { type: "integer" }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const m = await fetchMeta(); - if (m.disableRecommendedTimeline) { - if (user == null || !(user.isAdmin || user.isModerator)) { - throw new ApiError(meta.errors.rtlDisabled); - } - } - - //#region Construct query - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - ps.sinceId, - ps.untilId, - ps.sinceDate, - ps.untilDate, - ) - .andWhere( - `(note.userHost = ANY ('{"${m.recommendedInstances.join('","')}"}'))`, - ) - .andWhere("(note.visibility = 'public')") - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner"); - - generateChannelQuery(query, user); - generateRepliesQuery(query, user); - generateVisibilityQuery(query, user); - if (user) generateMutedUserQuery(query, user); - if (user) generateMutedNoteQuery(query, user); - if (user) generateBlockedUserQuery(query, user); - if (user) generateMutedUserRenotesQueryForNotes(query, user); - - if (ps.withFiles) { - query.andWhere("note.fileIds != '{}'"); - } - - if (ps.fileType != null) { - query.andWhere("note.fileIds != '{}'"); - query.andWhere( - new Brackets((qb) => { - for (const type of ps.fileType!) { - const i = ps.fileType!.indexOf(type); - qb.orWhere(`:type${i} = ANY(note.attachedFileTypes)`, { - [`type${i}`]: type, - }); - } - }), - ); - - if (ps.excludeNsfw) { - query.andWhere("note.cw IS NULL"); - query.andWhere( - '0 = (SELECT COUNT(*) FROM drive_file df WHERE df.id = ANY(note."fileIds") AND df."isSensitive" = TRUE)', - ); - } - } - //#endregion - - process.nextTick(() => { - if (user) { - activeUsersChart.read(user); - } - }); - - // We fetch more than requested because some may be filtered out, and if there's less than - // requested, the pagination stops. - const found = []; - const take = Math.floor(ps.limit * 1.5); - let skip = 0; - while (found.length < ps.limit) { - const notes = await query.take(take).skip(skip).getMany(); - found.push(...(await Notes.packMany(notes, user))); - skip += take; - if (notes.length < take) break; - } - - if (found.length > ps.limit) { - found.length = ps.limit; - } - - return found; -}); diff --git a/packages/backend/src/server/api/endpoints/notes/renotes.ts b/packages/backend/src/server/api/endpoints/notes/renotes.ts deleted file mode 100644 index f313616be2..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/renotes.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { Notes } from "@/models/index.js"; -import define from "../../define.js"; -import { getNote } from "../../common/getters.js"; -import { ApiError } from "../../error.js"; -import { generateVisibilityQuery } from "../../common/generate-visibility-query.js"; -import { generateMutedUserQuery } from "../../common/generate-muted-user-query.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { generateBlockedUserQuery } from "../../common/generate-block-query.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "12908022-2e21-46cd-ba6a-3edaf6093f46", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - ps.sinceId, - ps.untilId, - ) - .andWhere("note.renoteId = :renoteId", { renoteId: note.id }) - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner"); - - generateVisibilityQuery(query, user); - if (user) generateMutedUserQuery(query, user); - if (user) generateBlockedUserQuery(query, user); - - // We fetch more than requested because some may be filtered out, and if there's less than - // requested, the pagination stops. - const found = []; - const take = Math.floor(ps.limit * 1.5); - let skip = 0; - while (found.length < ps.limit) { - const notes = await query.take(take).skip(skip).getMany(); - found.push(...(await Notes.packMany(notes, user))); - skip += take; - if (notes.length < take) break; - } - - if (found.length > ps.limit) { - found.length = ps.limit; - } - - return found; -}); diff --git a/packages/backend/src/server/api/endpoints/notes/replies.ts b/packages/backend/src/server/api/endpoints/notes/replies.ts deleted file mode 100644 index 5ea4d479c5..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/replies.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { Notes } from "@/models/index.js"; -import define from "../../define.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { generateVisibilityQuery } from "../../common/generate-visibility-query.js"; -import { generateMutedUserQuery } from "../../common/generate-muted-user-query.js"; -import { generateBlockedUserQuery } from "../../common/generate-block-query.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - ps.sinceId, - ps.untilId, - ) - .andWhere("note.replyId = :replyId", { replyId: ps.noteId }) - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner"); - - generateVisibilityQuery(query, user); - if (user) generateMutedUserQuery(query, user); - if (user) generateBlockedUserQuery(query, user); - - // We fetch more than requested because some may be filtered out, and if there's less than - // requested, the pagination stops. - const found = []; - const take = Math.floor(ps.limit * 1.5); - let skip = 0; - while (found.length < ps.limit) { - const notes = await query.take(take).skip(skip).getMany(); - found.push(...(await Notes.packMany(notes, user))); - skip += take; - if (notes.length < take) break; - } - - if (found.length > ps.limit) { - found.length = ps.limit; - } - - return found; -}); diff --git a/packages/backend/src/server/api/endpoints/notes/search-by-tag.ts b/packages/backend/src/server/api/endpoints/notes/search-by-tag.ts deleted file mode 100644 index f988acaa51..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/search-by-tag.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { Brackets } from "typeorm"; -import { Notes } from "@/models/index.js"; -import { safeForSql } from "@/misc/safe-for-sql.js"; -import { normalizeForSearch } from "@/misc/normalize-for-search.js"; -import define from "../../define.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { generateMutedUserQuery } from "../../common/generate-muted-user-query.js"; -import { generateVisibilityQuery } from "../../common/generate-visibility-query.js"; -import { generateBlockedUserQuery } from "../../common/generate-block-query.js"; - -export const meta = { - tags: ["notes", "hashtags"], - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - reply: { type: "boolean", nullable: true, default: null }, - renote: { type: "boolean", nullable: true, default: null }, - withFiles: { - type: "boolean", - default: false, - description: "Only show notes that have attached files.", - }, - poll: { type: "boolean", nullable: true, default: null }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - }, - anyOf: [ - { - properties: { - tag: { type: "string", minLength: 1 }, - }, - required: ["tag"], - }, - { - properties: { - query: { - type: "array", - description: - "The outer arrays are chained with OR, the inner arrays are chained with AND.", - items: { - type: "array", - items: { - type: "string", - minLength: 1, - }, - minItems: 1, - }, - minItems: 1, - }, - }, - required: ["query"], - }, - ], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - ps.sinceId, - ps.untilId, - ) - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner"); - - generateVisibilityQuery(query, me); - if (me) generateMutedUserQuery(query, me); - if (me) generateBlockedUserQuery(query, me); - - try { - if (ps.tag) { - if (!safeForSql(normalizeForSearch(ps.tag))) throw "Injection"; - query.andWhere(`'{"${normalizeForSearch(ps.tag)}"}' <@ note.tags`); - } else { - query.andWhere( - new Brackets((qb) => { - for (const tags of ps.query!) { - qb.orWhere( - new Brackets((qb) => { - for (const tag of tags) { - if (!safeForSql(normalizeForSearch(ps.tag))) - throw "Injection"; - qb.andWhere(`'{"${normalizeForSearch(tag)}"}' <@ note.tags`); - } - }), - ); - } - }), - ); - } - } catch (e) { - if (e.message === "Injection") return []; - throw e; - } - - if (ps.reply != null) { - if (ps.reply) { - query.andWhere("note.replyId IS NOT NULL"); - } else { - query.andWhere("note.replyId IS NULL"); - } - } - - if (ps.renote != null) { - if (ps.renote) { - query.andWhere("note.renoteId IS NOT NULL"); - } else { - query.andWhere("note.renoteId IS NULL"); - } - } - - if (ps.withFiles) { - query.andWhere("note.fileIds != '{}'"); - } - - if (ps.poll != null) { - if (ps.poll) { - query.andWhere("note.hasPoll = TRUE"); - } else { - query.andWhere("note.hasPoll = FALSE"); - } - } - - // We fetch more than requested because some may be filtered out, and if there's less than - // requested, the pagination stops. - const found = []; - const take = Math.floor(ps.limit * 1.5); - let skip = 0; - while (found.length < ps.limit) { - const notes = await query.take(take).skip(skip).getMany(); - found.push(...(await Notes.packMany(notes, me))); - skip += take; - if (notes.length < take) break; - } - - if (found.length > ps.limit) { - found.length = ps.limit; - } - - return found; -}); diff --git a/packages/backend/src/server/api/endpoints/notes/search.ts b/packages/backend/src/server/api/endpoints/notes/search.ts deleted file mode 100644 index 8f563c384f..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/search.ts +++ /dev/null @@ -1,254 +0,0 @@ -import { In } from "typeorm"; -import { Notes } from "@/models/index.js"; -import { Note } from "@/models/entities/note.js"; -import config from "@/config/index.js"; -import es from "../../../../db/elasticsearch.js"; -import sonic from "../../../../db/sonic.js"; -import define from "../../define.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { generateVisibilityQuery } from "../../common/generate-visibility-query.js"; -import { generateMutedUserQuery } from "../../common/generate-muted-user-query.js"; -import { generateBlockedUserQuery } from "../../common/generate-block-query.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, - - errors: {}, -} as const; - -export const paramDef = { - type: "object", - properties: { - query: { type: "string" }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - offset: { type: "integer", default: 0 }, - host: { - type: "string", - nullable: true, - description: "The local host is represented with `null`.", - }, - userId: { - type: "string", - format: "misskey:id", - nullable: true, - default: null, - }, - channelId: { - type: "string", - format: "misskey:id", - nullable: true, - default: null, - }, - }, - required: ["query"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - if (es == null && sonic == null) { - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - ps.sinceId, - ps.untilId, - ); - - if (ps.userId) { - query.andWhere("note.userId = :userId", { userId: ps.userId }); - } else if (ps.channelId) { - query.andWhere("note.channelId = :channelId", { - channelId: ps.channelId, - }); - } - - query - .andWhere("note.text ILIKE :q", { q: `%${ps.query}%` }) - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner"); - - generateVisibilityQuery(query, me); - if (me) generateMutedUserQuery(query, me); - if (me) generateBlockedUserQuery(query, me); - - const notes: Note[] = await query.take(ps.limit).getMany(); - - return await Notes.packMany(notes, me); - } else if (sonic) { - let start = 0; - const chunkSize = 100; - - // Use sonic to fetch and step through all search results that could match the requirements - const ids = []; - while (true) { - const results = await sonic.search.query( - sonic.collection, - sonic.bucket, - ps.query, - { - limit: chunkSize, - offset: start, - }, - ); - - start += chunkSize; - - if (results.length === 0) { - break; - } - - const res = results - .map((k) => JSON.parse(k)) - .filter((key) => { - if (ps.userId && key.userId !== ps.userId) { - return false; - } - if (ps.channelId && key.channelId !== ps.channelId) { - return false; - } - if (ps.sinceId && key.id <= ps.sinceId) { - return false; - } - if (ps.untilId && key.id >= ps.untilId) { - return false; - } - return true; - }) - .map((key) => key.id); - - ids.push(...res); - } - - // Sort all the results by note id DESC (newest first) - ids.sort((a, b) => b - a); - - // Fetch the notes from the database until we have enough to satisfy the limit - start = 0; - const found = []; - while (found.length < ps.limit && start < ids.length) { - const chunk = ids.slice(start, start + chunkSize); - const notes: Note[] = await Notes.find({ - where: { - id: In(chunk), - }, - order: { - id: "DESC", - }, - }); - - // The notes are checked for visibility and muted/blocked users when packed - found.push(...(await Notes.packMany(notes, me))); - start += chunkSize; - } - - // If we have more results than the limit, trim them - if (found.length > ps.limit) { - found.length = ps.limit; - } - - return found; - } else { - const userQuery = - ps.userId != null - ? [ - { - term: { - userId: ps.userId, - }, - }, - ] - : []; - - const hostQuery = - ps.userId == null - ? ps.host === null - ? [ - { - bool: { - must_not: { - exists: { - field: "userHost", - }, - }, - }, - }, - ] - : ps.host !== undefined - ? [ - { - term: { - userHost: ps.host, - }, - }, - ] - : [] - : []; - - const result = await es.search({ - index: config.elasticsearch.index || "misskey_note", - body: { - size: ps.limit, - from: ps.offset, - query: { - bool: { - must: [ - { - simple_query_string: { - fields: ["text"], - query: ps.query.toLowerCase(), - default_operator: "and", - }, - }, - ...hostQuery, - ...userQuery, - ], - }, - }, - sort: [ - { - _doc: "desc", - }, - ], - }, - }); - - const hits = result.body.hits.hits.map((hit: any) => hit._id); - - if (hits.length === 0) return []; - - // Fetch found notes - const notes = await Notes.find({ - where: { - id: In(hits), - }, - order: { - id: -1, - }, - }); - - return await Notes.packMany(notes, me); - } -}); diff --git a/packages/backend/src/server/api/endpoints/notes/show.ts b/packages/backend/src/server/api/endpoints/notes/show.ts deleted file mode 100644 index 39d128134f..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/show.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { Notes } from "@/models/index.js"; -import define from "../../define.js"; -import { getNote } from "../../common/getters.js"; -import { ApiError } from "../../error.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "24fcbfc6-2e37-42b6-8388-c29b3861a08d", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - return await Notes.pack(note, user, { - // FIXME: packing with detail may throw an error if the reply or renote is not visible (#8774) - detail: true, - }).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); -}); diff --git a/packages/backend/src/server/api/endpoints/notes/state.ts b/packages/backend/src/server/api/endpoints/notes/state.ts deleted file mode 100644 index 630b2a8007..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/state.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { - NoteFavorites, - Notes, - NoteThreadMutings, - NoteWatchings, -} from "@/models/index.js"; -import { getNote } from "../../common/getters.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: true, - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - isFavorited: { - type: "boolean", - optional: false, - nullable: false, - }, - isWatching: { - type: "boolean", - optional: false, - nullable: false, - }, - isMutedThread: { - type: "boolean", - optional: false, - nullable: false, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const note = await getNote(ps.noteId, user); - - const [favorite, watching, threadMuting] = await Promise.all([ - NoteFavorites.count({ - where: { - userId: user.id, - noteId: note.id, - }, - take: 1, - }), - NoteWatchings.count({ - where: { - userId: user.id, - noteId: note.id, - }, - take: 1, - }), - NoteThreadMutings.count({ - where: { - userId: user.id, - threadId: note.threadId || note.id, - }, - take: 1, - }), - ]); - - return { - isFavorited: favorite !== 0, - isWatching: watching !== 0, - isMutedThread: threadMuting !== 0, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/notes/thread-muting/create.ts b/packages/backend/src/server/api/endpoints/notes/thread-muting/create.ts deleted file mode 100644 index e4803cc291..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/thread-muting/create.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { Notes, NoteThreadMutings } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import readNote from "@/services/note/read.js"; -import define from "../../../define.js"; -import { getNote } from "../../../common/getters.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: true, - - kind: "write:account", - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "5ff67ada-ed3b-2e71-8e87-a1a421e177d2", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - const mutedNotes = await Notes.find({ - where: [ - { - id: note.threadId || note.id, - }, - { - threadId: note.threadId || note.id, - }, - ], - }); - - await readNote(user.id, mutedNotes); - - await NoteThreadMutings.insert({ - id: genId(), - createdAt: new Date(), - threadId: note.threadId || note.id, - userId: user.id, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/notes/thread-muting/delete.ts b/packages/backend/src/server/api/endpoints/notes/thread-muting/delete.ts deleted file mode 100644 index c06fd59ba5..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/thread-muting/delete.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { NoteThreadMutings } from "@/models/index.js"; -import define from "../../../define.js"; -import { getNote } from "../../../common/getters.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: true, - - kind: "write:account", - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "bddd57ac-ceb3-b29d-4334-86ea5fae481a", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - await NoteThreadMutings.delete({ - threadId: note.threadId || note.id, - userId: user.id, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/notes/timeline.ts b/packages/backend/src/server/api/endpoints/notes/timeline.ts deleted file mode 100644 index f85c0cfd32..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/timeline.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { Brackets } from "typeorm"; -import { Notes, Followings } from "@/models/index.js"; -import { activeUsersChart } from "@/services/chart/index.js"; -import define from "../../define.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { generateVisibilityQuery } from "../../common/generate-visibility-query.js"; -import { generateMutedUserQuery } from "../../common/generate-muted-user-query.js"; -import { generateRepliesQuery } from "../../common/generate-replies-query.js"; -import { generateMutedNoteQuery } from "../../common/generate-muted-note-query.js"; -import { generateChannelQuery } from "../../common/generate-channel-query.js"; -import { generateBlockedUserQuery } from "../../common/generate-block-query.js"; -import { generateMutedUserRenotesQueryForNotes } from "../../common/generated-muted-renote-query.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - sinceDate: { type: "integer" }, - untilDate: { type: "integer" }, - includeMyRenotes: { type: "boolean", default: true }, - includeRenotedMyNotes: { type: "boolean", default: true }, - includeLocalRenotes: { type: "boolean", default: true }, - withFiles: { - type: "boolean", - default: false, - description: "Only show notes that have attached files.", - }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const hasFollowing = - (await Followings.count({ - where: { - followerId: user.id, - }, - take: 1, - })) !== 0; - - //#region Construct query - const followingQuery = Followings.createQueryBuilder("following") - .select("following.followeeId") - .where("following.followerId = :followerId", { followerId: user.id }); - - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - ps.sinceId, - ps.untilId, - ps.sinceDate, - ps.untilDate, - ) - .andWhere( - new Brackets((qb) => { - qb.where("note.userId = :meId", { meId: user.id }); - if (hasFollowing) - qb.orWhere(`note.userId IN (${followingQuery.getQuery()})`); - }), - ) - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner") - .setParameters(followingQuery.getParameters()); - - generateChannelQuery(query, user); - generateRepliesQuery(query, user); - generateVisibilityQuery(query, user); - generateMutedUserQuery(query, user); - generateMutedNoteQuery(query, user); - generateBlockedUserQuery(query, user); - generateMutedUserRenotesQueryForNotes(query, user); - - if (ps.includeMyRenotes === false) { - query.andWhere( - new Brackets((qb) => { - qb.orWhere("note.userId != :meId", { meId: user.id }); - qb.orWhere("note.renoteId IS NULL"); - qb.orWhere("note.text IS NOT NULL"); - qb.orWhere("note.fileIds != '{}'"); - qb.orWhere( - '0 < (SELECT COUNT(*) FROM poll WHERE poll."noteId" = note.id)', - ); - }), - ); - } - - if (ps.includeRenotedMyNotes === false) { - query.andWhere( - new Brackets((qb) => { - qb.orWhere("note.renoteUserId != :meId", { meId: user.id }); - qb.orWhere("note.renoteId IS NULL"); - qb.orWhere("note.text IS NOT NULL"); - qb.orWhere("note.fileIds != '{}'"); - qb.orWhere( - '0 < (SELECT COUNT(*) FROM poll WHERE poll."noteId" = note.id)', - ); - }), - ); - } - - if (ps.includeLocalRenotes === false) { - query.andWhere( - new Brackets((qb) => { - qb.orWhere("note.renoteUserHost IS NOT NULL"); - qb.orWhere("note.renoteId IS NULL"); - qb.orWhere("note.text IS NOT NULL"); - qb.orWhere("note.fileIds != '{}'"); - qb.orWhere( - '0 < (SELECT COUNT(*) FROM poll WHERE poll."noteId" = note.id)', - ); - }), - ); - } - - if (ps.withFiles) { - query.andWhere("note.fileIds != '{}'"); - } - //#endregion - - process.nextTick(() => { - activeUsersChart.read(user); - }); - - // We fetch more than requested because some may be filtered out, and if there's less than - // requested, the pagination stops. - const found = []; - const take = Math.floor(ps.limit * 1.5); - let skip = 0; - while (found.length < ps.limit) { - const notes = await query.take(take).skip(skip).getMany(); - found.push(...(await Notes.packMany(notes, user))); - skip += take; - if (notes.length < take) break; - } - - if (found.length > ps.limit) { - found.length = ps.limit; - } - - return found; -}); diff --git a/packages/backend/src/server/api/endpoints/notes/translate.ts b/packages/backend/src/server/api/endpoints/notes/translate.ts deleted file mode 100644 index c6415ceef2..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/translate.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { URLSearchParams } from "node:url"; -import fetch from "node-fetch"; -import config from "@/config/index.js"; -import { getAgentByUrl } from "@/misc/fetch.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { Notes } from "@/models/index.js"; -import { ApiError } from "../../error.js"; -import { getNote } from "../../common/getters.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "object", - optional: false, - nullable: false, - }, - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "bea9b03f-36e0-49c5-a4db-627a029f8971", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - targetLang: { type: "string" }, - }, - required: ["noteId", "targetLang"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - if (note.text == null) { - return 204; - } - - const instance = await fetchMeta(); - - if (instance.deeplAuthKey == null) { - return 204; // TODO: 良い感じのエラー返す - } - - let targetLang = ps.targetLang; - if (targetLang.includes("-")) targetLang = targetLang.split("-")[0]; - - const params = new URLSearchParams(); - params.append("auth_key", instance.deeplAuthKey); - params.append("text", note.text); - params.append("target_lang", targetLang); - - const endpoint = instance.deeplIsPro - ? "https://api.deepl.com/v2/translate" - : "https://api-free.deepl.com/v2/translate"; - - const res = await fetch(endpoint, { - method: "POST", - headers: { - "Content-Type": "application/x-www-form-urlencoded", - "User-Agent": config.userAgent, - Accept: "application/json, */*", - }, - body: params, - // TODO - //timeout: 10000, - agent: getAgentByUrl, - }); - - const json = (await res.json()) as { - translations: { - detected_source_language: string; - text: string; - }[]; - }; - - return { - sourceLang: json.translations[0].detected_source_language, - text: json.translations[0].text, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/notes/unrenote.ts b/packages/backend/src/server/api/endpoints/notes/unrenote.ts deleted file mode 100644 index a30a19f190..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/unrenote.ts +++ /dev/null @@ -1,53 +0,0 @@ -import deleteNote from "@/services/note/delete.js"; -import { Notes, Users } from "@/models/index.js"; -import define from "../../define.js"; -import { getNote } from "../../common/getters.js"; -import { ApiError } from "../../error.js"; -import { SECOND, HOUR } from "@/const.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: true, - - kind: "write:notes", - - limit: { - duration: HOUR, - max: 300, - minInterval: SECOND, - }, - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "efd4a259-2442-496b-8dd7-b255aa1a160f", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - const renotes = await Notes.findBy({ - userId: user.id, - renoteId: note.id, - }); - - for (const note of renotes) { - deleteNote(await Users.findOneByOrFail({ id: user.id }), note); - } -}); diff --git a/packages/backend/src/server/api/endpoints/notes/user-list-timeline.ts b/packages/backend/src/server/api/endpoints/notes/user-list-timeline.ts deleted file mode 100644 index 03f5cee3f3..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/user-list-timeline.ts +++ /dev/null @@ -1,164 +0,0 @@ -import { Brackets } from "typeorm"; -import { UserLists, UserListJoinings, Notes } from "@/models/index.js"; -import { activeUsersChart } from "@/services/chart/index.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { generateVisibilityQuery } from "../../common/generate-visibility-query.js"; - -export const meta = { - tags: ["notes", "lists"], - - requireCredential: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, - - errors: { - noSuchList: { - message: "No such list.", - code: "NO_SUCH_LIST", - id: "8fb1fbd5-e476-4c37-9fb0-43d55b63a2ff", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - listId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - sinceDate: { type: "integer" }, - untilDate: { type: "integer" }, - includeMyRenotes: { type: "boolean", default: true }, - includeRenotedMyNotes: { type: "boolean", default: true }, - includeLocalRenotes: { type: "boolean", default: true }, - withFiles: { - type: "boolean", - default: false, - description: "Only show notes that have attached files.", - }, - }, - required: ["listId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const list = await UserLists.findOneBy({ - id: ps.listId, - userId: user.id, - }); - - if (list == null) { - throw new ApiError(meta.errors.noSuchList); - } - - //#region Construct query - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - ps.sinceId, - ps.untilId, - ) - .innerJoin( - UserListJoinings.metadata.targetName, - "userListJoining", - "userListJoining.userId = note.userId", - ) - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner") - .andWhere("userListJoining.userListId = :userListId", { - userListId: list.id, - }); - - generateVisibilityQuery(query, user); - - if (ps.includeMyRenotes === false) { - query.andWhere( - new Brackets((qb) => { - qb.orWhere("note.userId != :meId", { meId: user.id }); - qb.orWhere("note.renoteId IS NULL"); - qb.orWhere("note.text IS NOT NULL"); - qb.orWhere("note.fileIds != '{}'"); - qb.orWhere( - '0 < (SELECT COUNT(*) FROM poll WHERE poll."noteId" = note.id)', - ); - }), - ); - } - - if (ps.includeRenotedMyNotes === false) { - query.andWhere( - new Brackets((qb) => { - qb.orWhere("note.renoteUserId != :meId", { meId: user.id }); - qb.orWhere("note.renoteId IS NULL"); - qb.orWhere("note.text IS NOT NULL"); - qb.orWhere("note.fileIds != '{}'"); - qb.orWhere( - '0 < (SELECT COUNT(*) FROM poll WHERE poll."noteId" = note.id)', - ); - }), - ); - } - - if (ps.includeLocalRenotes === false) { - query.andWhere( - new Brackets((qb) => { - qb.orWhere("note.renoteUserHost IS NOT NULL"); - qb.orWhere("note.renoteId IS NULL"); - qb.orWhere("note.text IS NOT NULL"); - qb.orWhere("note.fileIds != '{}'"); - qb.orWhere( - '0 < (SELECT COUNT(*) FROM poll WHERE poll."noteId" = note.id)', - ); - }), - ); - } - - if (ps.withFiles) { - query.andWhere("note.fileIds != '{}'"); - } - //#endregion - - process.nextTick(() => { - if (user) { - activeUsersChart.read(user); - } - }); - - // We fetch more than requested because some may be filtered out, and if there's less than - // requested, the pagination stops. - const found = []; - const take = Math.floor(ps.limit * 1.5); - let skip = 0; - while (found.length < ps.limit) { - const notes = await query.take(take).skip(skip).getMany(); - found.push(...(await Notes.packMany(notes, user))); - skip += take; - if (notes.length < take) break; - } - - if (found.length > ps.limit) { - found.length = ps.limit; - } - - return found; -}); diff --git a/packages/backend/src/server/api/endpoints/notes/watching/create.ts b/packages/backend/src/server/api/endpoints/notes/watching/create.ts deleted file mode 100644 index f8921099a1..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/watching/create.ts +++ /dev/null @@ -1,38 +0,0 @@ -import watch from "@/services/note/watch.js"; -import define from "../../../define.js"; -import { getNote } from "../../../common/getters.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: true, - - kind: "write:account", - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "ea0e37a6-90a3-4f58-ba6b-c328ca206fc7", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - await watch(user.id, note); -}); diff --git a/packages/backend/src/server/api/endpoints/notes/watching/delete.ts b/packages/backend/src/server/api/endpoints/notes/watching/delete.ts deleted file mode 100644 index b441ad74b9..0000000000 --- a/packages/backend/src/server/api/endpoints/notes/watching/delete.ts +++ /dev/null @@ -1,38 +0,0 @@ -import unwatch from "@/services/note/unwatch.js"; -import define from "../../../define.js"; -import { getNote } from "../../../common/getters.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: true, - - kind: "write:account", - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "09b3695c-f72c-4731-a428-7cff825fc82e", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - await unwatch(user.id, note); -}); diff --git a/packages/backend/src/server/api/endpoints/notifications/create.ts b/packages/backend/src/server/api/endpoints/notifications/create.ts deleted file mode 100644 index bc5723369c..0000000000 --- a/packages/backend/src/server/api/endpoints/notifications/create.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { createNotification } from "@/services/create-notification.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["notifications"], - - requireCredential: true, - - kind: "write:notifications", - - errors: {}, -} as const; - -export const paramDef = { - type: "object", - properties: { - body: { type: "string" }, - header: { type: "string", nullable: true }, - icon: { type: "string", nullable: true }, - }, - required: ["body"], -} as const; - -export default define(meta, paramDef, async (ps, user, token) => { - createNotification(user.id, "app", { - appAccessTokenId: token ? token.id : null, - customBody: ps.body, - customHeader: ps.header, - customIcon: ps.icon, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/notifications/mark-all-as-read.ts b/packages/backend/src/server/api/endpoints/notifications/mark-all-as-read.ts deleted file mode 100644 index e0888ad752..0000000000 --- a/packages/backend/src/server/api/endpoints/notifications/mark-all-as-read.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { publishMainStream } from "@/services/stream.js"; -import { pushNotification } from "@/services/push-notification.js"; -import { Notifications } from "@/models/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["notifications", "account"], - - requireCredential: true, - - kind: "write:notifications", -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Update documents - await Notifications.update( - { - notifieeId: user.id, - isRead: false, - }, - { - isRead: true, - }, - ); - - // 全ての通知を読みましたよというイベントを発行 - publishMainStream(user.id, "readAllNotifications"); - pushNotification(user.id, "readAllNotifications", undefined); -}); diff --git a/packages/backend/src/server/api/endpoints/notifications/read.ts b/packages/backend/src/server/api/endpoints/notifications/read.ts deleted file mode 100644 index 9efb2fcc0b..0000000000 --- a/packages/backend/src/server/api/endpoints/notifications/read.ts +++ /dev/null @@ -1,49 +0,0 @@ -import define from "../../define.js"; -import { readNotification } from "../../common/read-notification.js"; - -export const meta = { - tags: ["notifications", "account"], - - requireCredential: true, - - kind: "write:notifications", - - description: "Mark a notification as read.", - - errors: { - noSuchNotification: { - message: "No such notification.", - code: "NO_SUCH_NOTIFICATION", - id: "efa929d5-05b5-47d1-beec-e6a4dbed011e", - }, - }, -} as const; - -export const paramDef = { - oneOf: [ - { - type: "object", - properties: { - notificationId: { type: "string", format: "misskey:id" }, - }, - required: ["notificationId"], - }, - { - type: "object", - properties: { - notificationIds: { - type: "array", - items: { type: "string", format: "misskey:id" }, - maxItems: 100, - }, - }, - required: ["notificationIds"], - }, - ], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - if ("notificationId" in ps) - return readNotification(user.id, [ps.notificationId]); - return readNotification(user.id, ps.notificationIds); -}); diff --git a/packages/backend/src/server/api/endpoints/page-push.ts b/packages/backend/src/server/api/endpoints/page-push.ts deleted file mode 100644 index a0f1e912fc..0000000000 --- a/packages/backend/src/server/api/endpoints/page-push.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { publishMainStream } from "@/services/stream.js"; -import { Users, Pages } from "@/models/index.js"; -import define from "../define.js"; -import { ApiError } from "../error.js"; - -export const meta = { - requireCredential: true, - secure: true, - - errors: { - noSuchPage: { - message: "No such page.", - code: "NO_SUCH_PAGE", - id: "4a13ad31-6729-46b4-b9af-e86b265c2e74", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - pageId: { type: "string", format: "misskey:id" }, - event: { type: "string" }, - var: {}, - }, - required: ["pageId", "event"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const page = await Pages.findOneBy({ id: ps.pageId }); - if (page == null) { - throw new ApiError(meta.errors.noSuchPage); - } - - publishMainStream(page.userId, "pageEvent", { - pageId: ps.pageId, - event: ps.event, - var: ps.var, - userId: user.id, - user: await Users.pack( - user.id, - { id: page.userId }, - { - detail: true, - }, - ), - }); -}); diff --git a/packages/backend/src/server/api/endpoints/pages/create.ts b/packages/backend/src/server/api/endpoints/pages/create.ts deleted file mode 100644 index 716d3265cc..0000000000 --- a/packages/backend/src/server/api/endpoints/pages/create.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { Pages, DriveFiles } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import { Page } from "@/models/entities/page.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - tags: ["pages"], - - requireCredential: true, - - kind: "write:pages", - - limit: { - duration: HOUR, - max: 300, - }, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "Page", - }, - - errors: { - noSuchFile: { - message: "No such file.", - code: "NO_SUCH_FILE", - id: "b7b97489-0f66-4b12-a5ff-b21bd63f6e1c", - }, - nameAlreadyExists: { - message: "Specified name already exists.", - code: "NAME_ALREADY_EXISTS", - id: "4650348e-301c-499a-83c9-6aa988c66bc1", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - title: { type: "string" }, - name: { type: "string", minLength: 1 }, - summary: { type: "string", nullable: true }, - content: { - type: "array", - items: { - type: "object", - additionalProperties: true, - }, - }, - variables: { - type: "array", - items: { - type: "object", - additionalProperties: true, - }, - }, - script: { type: "string" }, - eyeCatchingImageId: { - type: "string", - format: "misskey:id", - nullable: true, - }, - font: { - type: "string", - enum: ["serif", "sans-serif"], - default: "sans-serif", - }, - alignCenter: { type: "boolean", default: false }, - isPublic: { type: "boolean", default: true }, - hideTitleWhenPinned: { type: "boolean", default: false }, - }, - required: ["title", "name", "content", "variables", "script"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - let eyeCatchingImage = null; - if (ps.eyeCatchingImageId != null) { - eyeCatchingImage = await DriveFiles.findOneBy({ - id: ps.eyeCatchingImageId, - userId: user.id, - }); - - if (eyeCatchingImage == null) { - throw new ApiError(meta.errors.noSuchFile); - } - } - - await Pages.findBy({ - userId: user.id, - name: ps.name, - }).then((result) => { - if (result.length > 0) { - throw new ApiError(meta.errors.nameAlreadyExists); - } - }); - - const page = await Pages.insert( - new Page({ - id: genId(), - createdAt: new Date(), - updatedAt: new Date(), - title: ps.title, - name: ps.name, - summary: ps.summary, - content: ps.content, - variables: ps.variables, - script: ps.script, - eyeCatchingImageId: eyeCatchingImage ? eyeCatchingImage.id : null, - userId: user.id, - visibility: "public", - alignCenter: ps.alignCenter, - hideTitleWhenPinned: ps.hideTitleWhenPinned, - font: ps.font, - isPublic: ps.isPublic, - }), - ).then((x) => Pages.findOneByOrFail(x.identifiers[0])); - - return await Pages.pack(page); -}); diff --git a/packages/backend/src/server/api/endpoints/pages/delete.ts b/packages/backend/src/server/api/endpoints/pages/delete.ts deleted file mode 100644 index 98b035f7c7..0000000000 --- a/packages/backend/src/server/api/endpoints/pages/delete.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { Pages } from "@/models/index.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; - -export const meta = { - tags: ["pages"], - - requireCredential: true, - - kind: "write:pages", - - errors: { - noSuchPage: { - message: "No such page.", - code: "NO_SUCH_PAGE", - id: "eb0c6e1d-d519-4764-9486-52a7e1c6392a", - }, - - accessDenied: { - message: "Access denied.", - code: "ACCESS_DENIED", - id: "8b741b3e-2c22-44b3-a15f-29949aa1601e", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - pageId: { type: "string", format: "misskey:id" }, - }, - required: ["pageId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const page = await Pages.findOneBy({ id: ps.pageId }); - if (page == null) { - throw new ApiError(meta.errors.noSuchPage); - } - if (page.userId !== user.id) { - throw new ApiError(meta.errors.accessDenied); - } - - await Pages.delete(page.id); -}); diff --git a/packages/backend/src/server/api/endpoints/pages/featured.ts b/packages/backend/src/server/api/endpoints/pages/featured.ts deleted file mode 100644 index a763465897..0000000000 --- a/packages/backend/src/server/api/endpoints/pages/featured.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { Pages } from "@/models/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["pages"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Page", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = Pages.createQueryBuilder("page") - .where("page.visibility = 'public'") - .andWhere("page.likedCount > 0") - .orderBy("page.likedCount", "DESC"); - - const pages = await query.take(10).getMany(); - - return await Pages.packMany(pages, me); -}); diff --git a/packages/backend/src/server/api/endpoints/pages/like.ts b/packages/backend/src/server/api/endpoints/pages/like.ts deleted file mode 100644 index f14ed39eb0..0000000000 --- a/packages/backend/src/server/api/endpoints/pages/like.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { Pages, PageLikes } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; - -export const meta = { - tags: ["pages"], - - requireCredential: true, - - kind: "write:page-likes", - - errors: { - noSuchPage: { - message: "No such page.", - code: "NO_SUCH_PAGE", - id: "cc98a8a2-0dc3-4123-b198-62c71df18ed3", - }, - - alreadyLiked: { - message: "The page has already been liked.", - code: "ALREADY_LIKED", - id: "cc98a8a2-0dc3-4123-b198-62c71df18ed3", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - pageId: { type: "string", format: "misskey:id" }, - }, - required: ["pageId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const page = await Pages.findOneBy({ id: ps.pageId }); - if (page == null) { - throw new ApiError(meta.errors.noSuchPage); - } - - // if already liked - const exist = await PageLikes.findOneBy({ - pageId: page.id, - userId: user.id, - }); - - if (exist != null) { - throw new ApiError(meta.errors.alreadyLiked); - } - - // Create like - await PageLikes.insert({ - id: genId(), - createdAt: new Date(), - pageId: page.id, - userId: user.id, - }); - - Pages.increment({ id: page.id }, "likedCount", 1); -}); diff --git a/packages/backend/src/server/api/endpoints/pages/show.ts b/packages/backend/src/server/api/endpoints/pages/show.ts deleted file mode 100644 index a25eb30b6d..0000000000 --- a/packages/backend/src/server/api/endpoints/pages/show.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { IsNull } from "typeorm"; -import { Pages, Users } from "@/models/index.js"; -import type { Page } from "@/models/entities/page.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; - -export const meta = { - tags: ["pages"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "object", - optional: false, - nullable: false, - ref: "Page", - }, - - errors: { - noSuchPage: { - message: "No such page.", - code: "NO_SUCH_PAGE", - id: "222120c0-3ead-4528-811b-b96f233388d7", - }, - }, -} as const; - -export const paramDef = { - type: "object", - anyOf: [ - { - properties: { - pageId: { type: "string", format: "misskey:id" }, - }, - required: ["pageId"], - }, - { - properties: { - name: { type: "string" }, - username: { type: "string" }, - }, - required: ["name", "username"], - }, - ], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - let page: Page | null = null; - - if (ps.pageId) { - page = await Pages.findOneBy({ id: ps.pageId }); - } else if (ps.name && ps.username) { - const author = await Users.findOneBy({ - host: IsNull(), - usernameLower: ps.username.toLowerCase(), - }); - if (author) { - page = await Pages.findOneBy({ - name: ps.name, - userId: author.id, - }); - } - } - - if (page == null) { - throw new ApiError(meta.errors.noSuchPage); - } - - if (!page.isPublic && (user == null || page.userId !== user.id)) { - throw new ApiError(meta.errors.noSuchPage); - } - - return await Pages.pack(page, user); -}); diff --git a/packages/backend/src/server/api/endpoints/pages/unlike.ts b/packages/backend/src/server/api/endpoints/pages/unlike.ts deleted file mode 100644 index 07bf3fbf48..0000000000 --- a/packages/backend/src/server/api/endpoints/pages/unlike.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { Pages, PageLikes } from "@/models/index.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; - -export const meta = { - tags: ["pages"], - - requireCredential: true, - - kind: "write:page-likes", - - errors: { - noSuchPage: { - message: "No such page.", - code: "NO_SUCH_PAGE", - id: "a0d41e20-1993-40bd-890e-f6e560ae648e", - }, - - notLiked: { - message: "You have not liked that page.", - code: "NOT_LIKED", - id: "f5e586b0-ce93-4050-b0e3-7f31af5259ee", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - pageId: { type: "string", format: "misskey:id" }, - }, - required: ["pageId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const page = await Pages.findOneBy({ id: ps.pageId }); - if (page == null) { - throw new ApiError(meta.errors.noSuchPage); - } - - const exist = await PageLikes.findOneBy({ - pageId: page.id, - userId: user.id, - }); - - if (exist == null) { - throw new ApiError(meta.errors.notLiked); - } - - // Delete like - await PageLikes.delete(exist.id); - - Pages.decrement({ id: page.id }, "likedCount", 1); -}); diff --git a/packages/backend/src/server/api/endpoints/pages/update.ts b/packages/backend/src/server/api/endpoints/pages/update.ts deleted file mode 100644 index 65e1b3b2d2..0000000000 --- a/packages/backend/src/server/api/endpoints/pages/update.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { Not } from "typeorm"; -import { Pages, DriveFiles } from "@/models/index.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - tags: ["pages"], - - requireCredential: true, - - kind: "write:pages", - - limit: { - duration: HOUR, - max: 300, - }, - - errors: { - noSuchPage: { - message: "No such page.", - code: "NO_SUCH_PAGE", - id: "21149b9e-3616-4778-9592-c4ce89f5a864", - }, - - accessDenied: { - message: "Access denied.", - code: "ACCESS_DENIED", - id: "3c15cd52-3b4b-4274-967d-6456fc4f792b", - }, - - noSuchFile: { - message: "No such file.", - code: "NO_SUCH_FILE", - id: "cfc23c7c-3887-490e-af30-0ed576703c82", - }, - nameAlreadyExists: { - message: "Specified name already exists.", - code: "NAME_ALREADY_EXISTS", - id: "2298a392-d4a1-44c5-9ebb-ac1aeaa5a9ab", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - pageId: { type: "string", format: "misskey:id" }, - title: { type: "string" }, - name: { type: "string", minLength: 1 }, - summary: { type: "string", nullable: true }, - content: { - type: "array", - items: { - type: "object", - additionalProperties: true, - }, - }, - variables: { - type: "array", - items: { - type: "object", - additionalProperties: true, - }, - }, - script: { type: "string" }, - eyeCatchingImageId: { - type: "string", - format: "misskey:id", - nullable: true, - }, - font: { type: "string", enum: ["serif", "sans-serif"] }, - alignCenter: { type: "boolean" }, - hideTitleWhenPinned: { type: "boolean" }, - isPublic: { type: "boolean" }, - }, - required: ["pageId", "title", "name", "content", "variables", "script"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const page = await Pages.findOneBy({ id: ps.pageId }); - if (page == null) { - throw new ApiError(meta.errors.noSuchPage); - } - if (page.userId !== user.id) { - throw new ApiError(meta.errors.accessDenied); - } - - let eyeCatchingImage = null; - if (ps.eyeCatchingImageId != null) { - eyeCatchingImage = await DriveFiles.findOneBy({ - id: ps.eyeCatchingImageId, - userId: user.id, - }); - - if (eyeCatchingImage == null) { - throw new ApiError(meta.errors.noSuchFile); - } - } - - await Pages.findBy({ - id: Not(ps.pageId), - userId: user.id, - name: ps.name, - }).then((result) => { - if (result.length > 0) { - throw new ApiError(meta.errors.nameAlreadyExists); - } - }); - - await Pages.update(page.id, { - updatedAt: new Date(), - title: ps.title, - name: ps.name === undefined ? page.name : ps.name, - summary: ps.name === undefined ? page.summary : ps.summary, - content: ps.content, - variables: ps.variables, - script: ps.script, - isPublic: ps.isPublic, - alignCenter: - ps.alignCenter === undefined ? page.alignCenter : ps.alignCenter, - hideTitleWhenPinned: - ps.hideTitleWhenPinned === undefined - ? page.hideTitleWhenPinned - : ps.hideTitleWhenPinned, - font: ps.font === undefined ? page.font : ps.font, - eyeCatchingImageId: - ps.eyeCatchingImageId === null - ? null - : ps.eyeCatchingImageId === undefined - ? page.eyeCatchingImageId - : eyeCatchingImage!.id, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/patrons.ts b/packages/backend/src/server/api/endpoints/patrons.ts deleted file mode 100644 index d6ac6c3971..0000000000 --- a/packages/backend/src/server/api/endpoints/patrons.ts +++ /dev/null @@ -1,28 +0,0 @@ -import define from "../define.js"; - -export const meta = { - tags: ["meta"], - description: "Get list of Calckey patrons from Codeberg", - - requireCredential: false, - requireCredentialPrivateMode: false, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - let patrons; - await fetch( - "https://codeberg.org/calckey/calckey/raw/branch/develop/patrons.json", - ) - .then((response) => response.json()) - .then((data) => { - patrons = data["patrons"]; - }); - - return patrons; -}); diff --git a/packages/backend/src/server/api/endpoints/ping.ts b/packages/backend/src/server/api/endpoints/ping.ts deleted file mode 100644 index c1f7e110bc..0000000000 --- a/packages/backend/src/server/api/endpoints/ping.ts +++ /dev/null @@ -1,32 +0,0 @@ -import define from "../define.js"; - -export const meta = { - requireCredential: false, - - tags: ["meta"], - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - pong: { - type: "number", - optional: false, - nullable: false, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - return { - pong: Date.now(), - }; -}); diff --git a/packages/backend/src/server/api/endpoints/pinned-users.ts b/packages/backend/src/server/api/endpoints/pinned-users.ts deleted file mode 100644 index 22020068ce..0000000000 --- a/packages/backend/src/server/api/endpoints/pinned-users.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { IsNull } from "typeorm"; -import { Users } from "@/models/index.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import * as Acct from "@/misc/acct.js"; -import type { User } from "@/models/entities/user.js"; -import define from "../define.js"; - -export const meta = { - tags: ["users"], - - requireCredential: false, - requireCredentialPrivateMode: false, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "UserDetailed", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const meta = await fetchMeta(); - - const users = await Promise.all( - meta.pinnedUsers - .map((acct) => Acct.parse(acct)) - .map((acct) => - Users.findOneBy({ - usernameLower: acct.username.toLowerCase(), - host: acct.host ?? IsNull(), - }), - ), - ); - - return await Users.packMany( - users.filter((x) => x !== undefined) as User[], - me, - { detail: true }, - ); -}); diff --git a/packages/backend/src/server/api/endpoints/promo/read.ts b/packages/backend/src/server/api/endpoints/promo/read.ts deleted file mode 100644 index 09c8cb6fab..0000000000 --- a/packages/backend/src/server/api/endpoints/promo/read.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { PromoReads } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { getNote } from "../../common/getters.js"; - -export const meta = { - tags: ["notes"], - - requireCredential: true, - - errors: { - noSuchNote: { - message: "No such note.", - code: "NO_SUCH_NOTE", - id: "d785b897-fcd3-4fe9-8fc3-b85c26e6c932", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - noteId: { type: "string", format: "misskey:id" }, - }, - required: ["noteId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const note = await getNote(ps.noteId, user).catch((err) => { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") - throw new ApiError(meta.errors.noSuchNote); - throw err; - }); - - const exist = await PromoReads.findOneBy({ - noteId: note.id, - userId: user.id, - }); - - if (exist != null) { - return; - } - - await PromoReads.insert({ - id: genId(), - createdAt: new Date(), - noteId: note.id, - userId: user.id, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/recommended-instances.ts b/packages/backend/src/server/api/endpoints/recommended-instances.ts deleted file mode 100644 index 8407afb1d3..0000000000 --- a/packages/backend/src/server/api/endpoints/recommended-instances.ts +++ /dev/null @@ -1,33 +0,0 @@ -// import { IsNull } from 'typeorm'; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import define from "../define.js"; - -export const meta = { - tags: ["meta"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "string", - optional: false, - nullable: false, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - const meta = await fetchMeta(); - const instances = await Promise.all(meta.recommendedInstances.map((x) => x)); - return instances; -}); diff --git a/packages/backend/src/server/api/endpoints/release.ts b/packages/backend/src/server/api/endpoints/release.ts deleted file mode 100644 index e5ebbb79a6..0000000000 --- a/packages/backend/src/server/api/endpoints/release.ts +++ /dev/null @@ -1,28 +0,0 @@ -import define from "../define.js"; - -export const meta = { - tags: ["meta"], - description: "Get release notes from Codeberg", - - requireCredential: false, - requireCredentialPrivateMode: false, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - let release; - - await fetch( - "https://codeberg.org/calckey/calckey/raw/branch/develop/release.json", - ) - .then((response) => response.json()) - .then((data) => { - release = data; - }); - return release; -}); diff --git a/packages/backend/src/server/api/endpoints/renote-mute/create.ts b/packages/backend/src/server/api/endpoints/renote-mute/create.ts deleted file mode 100644 index 857cbd9756..0000000000 --- a/packages/backend/src/server/api/endpoints/renote-mute/create.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { genId } from "@/misc/gen-id.js"; -import { RenoteMutings } from "@/models/index.js"; -import { RenoteMuting } from "@/models/entities/renote-muting.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { getUser } from "../../common/getters.js"; - -export const meta = { - tags: ["account"], - - requireCredential: true, - - kind: "write:mutes", - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "6fef56f3-e765-4957-88e5-c6f65329b8a5", - }, - - alreadyMuting: { - message: "You are already muting that user.", - code: "ALREADY_MUTING", - id: "7e7359cb-160c-4956-b08f-4d1c653cd007", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -// eslint-disable-next-line import/no-default-export -export default define(meta, paramDef, async (ps, user) => { - const muter = user; - - // Get mutee - const mutee = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - // Check if already muting - const exist = await RenoteMutings.findOneBy({ - muterId: muter.id, - muteeId: mutee.id, - }); - - if (exist != null) { - throw new ApiError(meta.errors.alreadyMuting); - } - - // Create mute - await RenoteMutings.insert({ - id: genId(), - createdAt: new Date(), - muterId: muter.id, - muteeId: mutee.id, - } as RenoteMuting); - - // publishUserEvent(user.id, "mute", mutee); -}); diff --git a/packages/backend/src/server/api/endpoints/renote-mute/delete.ts b/packages/backend/src/server/api/endpoints/renote-mute/delete.ts deleted file mode 100644 index fb4c972af0..0000000000 --- a/packages/backend/src/server/api/endpoints/renote-mute/delete.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { RenoteMutings } from "@/models/index.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { getUser } from "../../common/getters.js"; - -export const meta = { - tags: ["account"], - - requireCredential: true, - - kind: "write:mutes", - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "b851d00b-8ab1-4a56-8b1b-e24187cb48ef", - }, - - notMuting: { - message: "You are not muting that user.", - code: "NOT_MUTING", - id: "5467d020-daa9-4553-81e1-135c0c35a96d", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -// eslint-disable-next-line import/no-default-export -export default define(meta, paramDef, async (ps, user) => { - const muter = user; - - // Get mutee - const mutee = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - // Check not muting - const exist = await RenoteMutings.findOneBy({ - muterId: muter.id, - muteeId: mutee.id, - }); - - if (exist == null) { - throw new ApiError(meta.errors.notMuting); - } - - // Delete mute - await RenoteMutings.delete({ - id: exist.id, - }); - - // publishUserEvent(user.id, "unmute", mutee); -}); diff --git a/packages/backend/src/server/api/endpoints/renote-mute/list.ts b/packages/backend/src/server/api/endpoints/renote-mute/list.ts deleted file mode 100644 index 9149dd9753..0000000000 --- a/packages/backend/src/server/api/endpoints/renote-mute/list.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { RenoteMutings } from "@/models/index.js"; -import define from "../../define.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["account"], - - requireCredential: true, - - kind: "read:mutes", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "RenoteMuting", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 30 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: [], -} as const; - -// eslint-disable-next-line import/no-default-export -export default define(meta, paramDef, async (ps, me) => { - const query = makePaginationQuery( - RenoteMutings.createQueryBuilder("muting"), - ps.sinceId, - ps.untilId, - ).andWhere("muting.muterId = :meId", { meId: me.id }); - - const mutings = await query.take(ps.limit).getMany(); - - return await RenoteMutings.packMany(mutings, me); -}); diff --git a/packages/backend/src/server/api/endpoints/request-reset-password.ts b/packages/backend/src/server/api/endpoints/request-reset-password.ts deleted file mode 100644 index bac564c1d6..0000000000 --- a/packages/backend/src/server/api/endpoints/request-reset-password.ts +++ /dev/null @@ -1,76 +0,0 @@ -import rndstr from "rndstr"; -import { IsNull } from "typeorm"; -import { publishMainStream } from "@/services/stream.js"; -import config from "@/config/index.js"; -import { Users, UserProfiles, PasswordResetRequests } from "@/models/index.js"; -import { sendEmail } from "@/services/send-email.js"; -import { genId } from "@/misc/gen-id.js"; -import { ApiError } from "../error.js"; -import define from "../define.js"; -import { HOUR } from "@/const.js"; - -export const meta = { - tags: ["reset password"], - - requireCredential: false, - - description: "Request a users password to be reset.", - - limit: { - duration: HOUR, - max: 3, - }, - - errors: {}, -} as const; - -export const paramDef = { - type: "object", - properties: { - username: { type: "string" }, - email: { type: "string" }, - }, - required: ["username", "email"], -} as const; - -export default define(meta, paramDef, async (ps) => { - const user = await Users.findOneBy({ - usernameLower: ps.username.toLowerCase(), - host: IsNull(), - }); - - // 合致するユーザーが登録されていなかったら無視 - if (user == null) { - return; - } - - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - // 合致するメアドが登録されていなかったら無視 - if (profile.email !== ps.email) { - return; - } - - // メアドが認証されていなかったら無視 - if (!profile.emailVerified) { - return; - } - - const token = rndstr("a-z0-9", 64); - - await PasswordResetRequests.insert({ - id: genId(), - createdAt: new Date(), - userId: profile.userId, - token, - }); - - const link = `${config.url}/reset-password/${token}`; - - sendEmail( - ps.email, - "Password reset requested", - `To reset password, please click this link:<br><a href="${link}">${link}</a>`, - `To reset password, please click this link: ${link}`, - ); -}); diff --git a/packages/backend/src/server/api/endpoints/reset-db.ts b/packages/backend/src/server/api/endpoints/reset-db.ts deleted file mode 100644 index c64db7bca8..0000000000 --- a/packages/backend/src/server/api/endpoints/reset-db.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { resetDb } from "@/db/postgre.js"; -import define from "../define.js"; -import { ApiError } from "../error.js"; - -export const meta = { - tags: ["non-productive"], - - requireCredential: false, - - description: - "Only available when running with <code>NODE_ENV=testing</code>. Reset the database and flush Redis.", - - errors: {}, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - if (process.env.NODE_ENV !== "test") - throw new Error("NODE_ENV is not a test"); - - await resetDb(); - - await new Promise((resolve) => setTimeout(resolve, 1000)); -}); diff --git a/packages/backend/src/server/api/endpoints/reset-password.ts b/packages/backend/src/server/api/endpoints/reset-password.ts deleted file mode 100644 index f695ae41f1..0000000000 --- a/packages/backend/src/server/api/endpoints/reset-password.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { publishMainStream } from "@/services/stream.js"; -import { Users, UserProfiles, PasswordResetRequests } from "@/models/index.js"; -import define from "../define.js"; -import { ApiError } from "../error.js"; -import { hashPassword } from "@/misc/password.js"; - -export const meta = { - tags: ["reset password"], - - requireCredential: false, - - description: "Complete the password reset that was previously requested.", - - errors: {}, -} as const; - -export const paramDef = { - type: "object", - properties: { - token: { type: "string" }, - password: { type: "string" }, - }, - required: ["token", "password"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const req = await PasswordResetRequests.findOneByOrFail({ - token: ps.token, - }); - - // 発行してから30分以上経過していたら無効 - if (Date.now() - req.createdAt.getTime() > 1000 * 60 * 30) { - throw new Error(); // TODO - } - - // Generate hash of password - const hash = await hashPassword(ps.password); - - await UserProfiles.update(req.userId, { - password: hash, - }); - - PasswordResetRequests.delete(req.id); -}); diff --git a/packages/backend/src/server/api/endpoints/server-info.ts b/packages/backend/src/server/api/endpoints/server-info.ts deleted file mode 100644 index 1ce27e2621..0000000000 --- a/packages/backend/src/server/api/endpoints/server-info.ts +++ /dev/null @@ -1,36 +0,0 @@ -import * as os from "node:os"; -import si from "systeminformation"; -import define from "../define.js"; - -export const meta = { - requireCredential: false, - requireCredentialPrivateMode: true, - - tags: ["meta"], -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - const memStats = await si.mem(); - const fsStats = await si.fsSize(); - - return { - machine: os.hostname(), - cpu: { - model: os.cpus()[0].model, - cores: os.cpus().length, - }, - mem: { - total: memStats.total, - }, - fs: { - total: fsStats[0].size, - used: fsStats[0].used, - }, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/stats.ts b/packages/backend/src/server/api/endpoints/stats.ts deleted file mode 100644 index 8bd5597689..0000000000 --- a/packages/backend/src/server/api/endpoints/stats.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { Instances, NoteReactions, Notes, Users } from "@/models/index.js"; -import define from "../define.js"; -import {} from "@/services/chart/index.js"; -import { IsNull } from "typeorm"; - -export const meta = { - requireCredential: false, - requireCredentialPrivateMode: true, - - tags: ["meta"], - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - notesCount: { - type: "number", - optional: false, - nullable: false, - }, - originalNotesCount: { - type: "number", - optional: false, - nullable: false, - }, - usersCount: { - type: "number", - optional: false, - nullable: false, - }, - originalUsersCount: { - type: "number", - optional: false, - nullable: false, - }, - instances: { - type: "number", - optional: false, - nullable: false, - }, - driveUsageLocal: { - type: "number", - optional: false, - nullable: false, - }, - driveUsageRemote: { - type: "number", - optional: false, - nullable: false, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async () => { - const [ - notesCount, - originalNotesCount, - usersCount, - originalUsersCount, - reactionsCount, - //originalReactionsCount, - instances, - ] = await Promise.all([ - Notes.count({ cache: 3600000 }), // 1 hour - Notes.count({ where: { userHost: IsNull() }, cache: 3600000 }), - Users.count({ cache: 3600000 }), - Users.count({ where: { host: IsNull() }, cache: 3600000 }), - NoteReactions.count({ cache: 3600000 }), // 1 hour - //NoteReactions.count({ where: { userHost: IsNull() }, cache: 3600000 }), - Instances.count({ cache: 3600000 }), - ]); - - return { - notesCount, - originalNotesCount, - usersCount, - originalUsersCount, - reactionsCount, - //originalReactionsCount, - instances, - driveUsageLocal: 0, - driveUsageRemote: 0, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/sw/register.ts b/packages/backend/src/server/api/endpoints/sw/register.ts deleted file mode 100644 index 42a35fb685..0000000000 --- a/packages/backend/src/server/api/endpoints/sw/register.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { genId } from "@/misc/gen-id.js"; -import { SwSubscriptions } from "@/models/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["account"], - - requireCredential: true, - - description: "Register to receive push notifications.", - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - state: { - type: "string", - optional: true, - nullable: false, - enum: ["already-subscribed", "subscribed"], - }, - key: { - type: "string", - optional: false, - nullable: true, - }, - userId: { - type: "string", - optional: false, - nullable: false, - }, - endpoint: { - type: "string", - optional: false, - nullable: false, - }, - sendReadMessage: { - type: "boolean", - optional: false, - nullable: false, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - endpoint: { type: "string" }, - auth: { type: "string" }, - publickey: { type: "string" }, - sendReadMessage: { type: "boolean", default: false }, - }, - required: ["endpoint", "auth", "publickey"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - // if already subscribed - const exist = await SwSubscriptions.findOneBy({ - userId: me.id, - endpoint: ps.endpoint, - auth: ps.auth, - publickey: ps.publickey, - }); - - const instance = await fetchMeta(true); - - if (exist != null) { - return { - state: "already-subscribed" as const, - key: instance.swPublicKey, - userId: me.id, - endpoint: exist.endpoint, - sendReadMessage: exist.sendReadMessage, - }; - } - - await SwSubscriptions.insert({ - id: genId(), - createdAt: new Date(), - userId: me.id, - endpoint: ps.endpoint, - auth: ps.auth, - publickey: ps.publickey, - sendReadMessage: ps.sendReadMessage, - }); - - return { - state: "subscribed" as const, - key: instance.swPublicKey, - userId: me.id, - endpoint: ps.endpoint, - sendReadMessage: ps.sendReadMessage, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/sw/show-registration.ts b/packages/backend/src/server/api/endpoints/sw/show-registration.ts deleted file mode 100644 index c7a9609cff..0000000000 --- a/packages/backend/src/server/api/endpoints/sw/show-registration.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { SwSubscriptions } from "@/models/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["account"], - - requireCredential: true, - - description: "Check push notification registration exists.", - - res: { - type: "object", - optional: false, - nullable: true, - properties: { - userId: { - type: "string", - optional: false, - nullable: false, - }, - endpoint: { - type: "string", - optional: false, - nullable: false, - }, - sendReadMessage: { - type: "boolean", - optional: false, - nullable: false, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - endpoint: { type: "string" }, - }, - required: ["endpoint"], -} as const; - -// eslint-disable-next-line import/no-default-export -export default define(meta, paramDef, async (ps, me) => { - const exist = await SwSubscriptions.findOneBy({ - userId: me.id, - endpoint: ps.endpoint, - }); - - if (exist != null) { - return { - userId: exist.userId, - endpoint: exist.endpoint, - sendReadMessage: exist.sendReadMessage, - }; - } - - return null; -}); diff --git a/packages/backend/src/server/api/endpoints/sw/unregister.ts b/packages/backend/src/server/api/endpoints/sw/unregister.ts deleted file mode 100644 index e2a40f51cb..0000000000 --- a/packages/backend/src/server/api/endpoints/sw/unregister.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { SwSubscriptions } from "@/models/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["account"], - - requireCredential: false, - - description: "Unregister from receiving push notifications.", -} as const; - -export const paramDef = { - type: "object", - properties: { - endpoint: { type: "string" }, - }, - required: ["endpoint"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - await SwSubscriptions.delete({ - ...(me ? { userId: me.id } : {}), - endpoint: ps.endpoint, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/sw/update-registration.ts b/packages/backend/src/server/api/endpoints/sw/update-registration.ts deleted file mode 100644 index 5ba53ee8a7..0000000000 --- a/packages/backend/src/server/api/endpoints/sw/update-registration.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { SwSubscriptions } from "@/models/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["account"], - - requireCredential: true, - - description: "Unregister from receiving push notifications.", -} as const; - -export const paramDef = { - type: "object", - properties: { - endpoint: { type: "string" }, - sendReadMessage: { type: "boolean" }, - }, - required: ["endpoint"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const swSubscription = await SwSubscriptions.findOneBy({ - userId: me.id, - endpoint: ps.endpoint, - }); - - if (swSubscription === null) { - throw new Error("No such registration"); - } - - if (ps.sendReadMessage !== undefined) { - swSubscription.sendReadMessage = ps.sendReadMessage; - } - - await SwSubscriptions.update(swSubscription.id, { - sendReadMessage: swSubscription.sendReadMessage, - }); - - return { - userId: swSubscription.userId, - endpoint: swSubscription.endpoint, - sendReadMessage: swSubscription.sendReadMessage, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/test.ts b/packages/backend/src/server/api/endpoints/test.ts deleted file mode 100644 index 2c43c61152..0000000000 --- a/packages/backend/src/server/api/endpoints/test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import define from "../define.js"; - -export const meta = { - tags: ["non-productive"], - - description: "Endpoint for testing input validation.", - - requireCredential: false, -} as const; - -export const paramDef = { - type: "object", - properties: { - required: { type: "boolean" }, - string: { type: "string" }, - default: { type: "string", default: "hello" }, - nullableDefault: { type: "string", nullable: true, default: "hello" }, - id: { type: "string", format: "misskey:id" }, - }, - required: ["required"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - return ps; -}); diff --git a/packages/backend/src/server/api/endpoints/username/available.ts b/packages/backend/src/server/api/endpoints/username/available.ts deleted file mode 100644 index f5aa4ed1ea..0000000000 --- a/packages/backend/src/server/api/endpoints/username/available.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { IsNull } from "typeorm"; -import { Users, UsedUsernames } from "@/models/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["users"], - - requireCredential: false, - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - available: { - type: "boolean", - optional: false, - nullable: false, - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - username: Users.localUsernameSchema, - }, - required: ["username"], -} as const; - -export default define(meta, paramDef, async (ps) => { - // Get exist - const exist = await Users.countBy({ - host: IsNull(), - usernameLower: ps.username.toLowerCase(), - }); - - const exist2 = await UsedUsernames.countBy({ - username: ps.username.toLowerCase(), - }); - - return { - available: exist === 0 && exist2 === 0, - }; -}); diff --git a/packages/backend/src/server/api/endpoints/users.ts b/packages/backend/src/server/api/endpoints/users.ts deleted file mode 100644 index f0a8670902..0000000000 --- a/packages/backend/src/server/api/endpoints/users.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { Users } from "@/models/index.js"; -import define from "../define.js"; -import { generateMutedUserQueryForUsers } from "../common/generate-muted-user-query.js"; -import { generateBlockQueryForUsers } from "../common/generate-block-query.js"; - -export const meta = { - tags: ["users"], - - requireCredential: true, - requireCredentialPrivateMode: true, - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "UserDetailed", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - offset: { type: "integer", default: 0 }, - sort: { - type: "string", - enum: [ - "+follower", - "-follower", - "+createdAt", - "-createdAt", - "+updatedAt", - "-updatedAt", - ], - }, - state: { - type: "string", - enum: ["all", "admin", "moderator", "adminOrModerator", "alive"], - default: "all", - }, - origin: { - type: "string", - enum: ["combined", "local", "remote"], - default: "local", - }, - hostname: { - type: "string", - nullable: true, - default: null, - description: "The local host is represented with `null`.", - }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = Users.createQueryBuilder("user"); - query.where("user.isExplorable = TRUE"); - - switch (ps.state) { - case "admin": - query.andWhere("user.isAdmin = TRUE"); - break; - case "moderator": - query.andWhere("user.isModerator = TRUE"); - break; - case "adminOrModerator": - query.andWhere("user.isAdmin = TRUE OR user.isModerator = TRUE"); - break; - case "alive": - query.andWhere("user.updatedAt > :date", { - date: new Date(Date.now() - 1000 * 60 * 60 * 24 * 5), - }); - break; - } - - switch (ps.origin) { - case "local": - query.andWhere("user.host IS NULL"); - break; - case "remote": - query.andWhere("user.host IS NOT NULL"); - break; - } - - if (ps.hostname) { - query.andWhere("user.host = :hostname", { - hostname: ps.hostname.toLowerCase(), - }); - } - - switch (ps.sort) { - case "+follower": - query.orderBy("user.followersCount", "DESC"); - break; - case "-follower": - query.orderBy("user.followersCount", "ASC"); - break; - case "+createdAt": - query.orderBy("user.createdAt", "DESC"); - break; - case "-createdAt": - query.orderBy("user.createdAt", "ASC"); - break; - case "+updatedAt": - query - .andWhere("user.updatedAt IS NOT NULL") - .orderBy("user.updatedAt", "DESC"); - break; - case "-updatedAt": - query - .andWhere("user.updatedAt IS NOT NULL") - .orderBy("user.updatedAt", "ASC"); - break; - default: - query.orderBy("user.id", "ASC"); - break; - } - - if (me) generateMutedUserQueryForUsers(query, me); - if (me) generateBlockQueryForUsers(query, me); - - query.take(ps.limit); - query.skip(ps.offset); - - const users = await query.getMany(); - - return await Users.packMany(users, me, { detail: true }); -}); diff --git a/packages/backend/src/server/api/endpoints/users/clips.ts b/packages/backend/src/server/api/endpoints/users/clips.ts deleted file mode 100644 index 0dc90b8f99..0000000000 --- a/packages/backend/src/server/api/endpoints/users/clips.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { Clips } from "@/models/index.js"; -import define from "../../define.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["users", "clips"], - requireCredentialPrivateMode: true, - - description: "Show all clips this user owns.", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Clip", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = makePaginationQuery( - Clips.createQueryBuilder("clip"), - ps.sinceId, - ps.untilId, - ) - .andWhere("clip.userId = :userId", { userId: ps.userId }) - .andWhere("clip.isPublic = true"); - - const clips = await query.take(ps.limit).getMany(); - - return await Clips.packMany(clips); -}); diff --git a/packages/backend/src/server/api/endpoints/users/followers.ts b/packages/backend/src/server/api/endpoints/users/followers.ts deleted file mode 100644 index 138343d9f4..0000000000 --- a/packages/backend/src/server/api/endpoints/users/followers.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { IsNull } from "typeorm"; -import { Users, Followings, UserProfiles } from "@/models/index.js"; -import { toPunyNullable } from "@/misc/convert-host.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["users"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - description: "Show everyone that follows this user.", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Following", - }, - }, - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "27fa5435-88ab-43de-9360-387de88727cd", - }, - - forbidden: { - message: "Forbidden.", - code: "FORBIDDEN", - id: "3c6a84db-d619-26af-ca14-06232a21df8a", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - }, - anyOf: [ - { - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], - }, - { - properties: { - username: { type: "string" }, - host: { - type: "string", - nullable: true, - description: "The local host is represented with `null`.", - }, - }, - required: ["username", "host"], - }, - ], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const user = await Users.findOneBy( - ps.userId != null - ? { id: ps.userId } - : { - usernameLower: ps.username!.toLowerCase(), - host: toPunyNullable(ps.host) ?? IsNull(), - }, - ); - - if (user == null) { - throw new ApiError(meta.errors.noSuchUser); - } - - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - if (profile.ffVisibility === "private") { - if (me == null || me.id !== user.id) { - throw new ApiError(meta.errors.forbidden); - } - } else if (profile.ffVisibility === "followers") { - if (me == null) { - throw new ApiError(meta.errors.forbidden); - } else if (me.id !== user.id) { - const following = await Followings.findOneBy({ - followeeId: user.id, - followerId: me.id, - }); - if (following == null) { - throw new ApiError(meta.errors.forbidden); - } - } - } - - const query = makePaginationQuery( - Followings.createQueryBuilder("following"), - ps.sinceId, - ps.untilId, - ) - .andWhere("following.followeeId = :userId", { userId: user.id }) - .innerJoinAndSelect("following.follower", "follower"); - - const followings = await query.take(ps.limit).getMany(); - - return await Followings.packMany(followings, me, { populateFollower: true }); -}); diff --git a/packages/backend/src/server/api/endpoints/users/following.ts b/packages/backend/src/server/api/endpoints/users/following.ts deleted file mode 100644 index 967379d0c4..0000000000 --- a/packages/backend/src/server/api/endpoints/users/following.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { IsNull } from "typeorm"; -import { Users, Followings, UserProfiles } from "@/models/index.js"; -import { toPunyNullable } from "@/misc/convert-host.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["users"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - description: "Show everyone that this user is following.", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Following", - }, - }, - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "63e4aba4-4156-4e53-be25-c9559e42d71b", - }, - - forbidden: { - message: "Forbidden.", - code: "FORBIDDEN", - id: "f6cdb0df-c19f-ec5c-7dbb-0ba84a1f92ba", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - }, - anyOf: [ - { - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], - }, - { - properties: { - username: { type: "string" }, - host: { - type: "string", - nullable: true, - description: "The local host is represented with `null`.", - }, - }, - required: ["username", "host"], - }, - ], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const user = await Users.findOneBy( - ps.userId != null - ? { id: ps.userId } - : { - usernameLower: ps.username!.toLowerCase(), - host: toPunyNullable(ps.host) ?? IsNull(), - }, - ); - - if (user == null) { - throw new ApiError(meta.errors.noSuchUser); - } - - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - if (profile.ffVisibility === "private") { - if (me == null || me.id !== user.id) { - throw new ApiError(meta.errors.forbidden); - } - } else if (profile.ffVisibility === "followers") { - if (me == null) { - throw new ApiError(meta.errors.forbidden); - } else if (me.id !== user.id) { - const following = await Followings.findOneBy({ - followeeId: user.id, - followerId: me.id, - }); - if (following == null) { - throw new ApiError(meta.errors.forbidden); - } - } - } - - const query = makePaginationQuery( - Followings.createQueryBuilder("following"), - ps.sinceId, - ps.untilId, - ) - .andWhere("following.followerId = :userId", { userId: user.id }) - .innerJoinAndSelect("following.followee", "followee"); - - const followings = await query.take(ps.limit).getMany(); - - return await Followings.packMany(followings, me, { populateFollowee: true }); -}); diff --git a/packages/backend/src/server/api/endpoints/users/gallery/posts.ts b/packages/backend/src/server/api/endpoints/users/gallery/posts.ts deleted file mode 100644 index 5d64fb4727..0000000000 --- a/packages/backend/src/server/api/endpoints/users/gallery/posts.ts +++ /dev/null @@ -1,45 +0,0 @@ -import define from "../../../define.js"; -import { GalleryPosts } from "@/models/index.js"; -import { makePaginationQuery } from "../../../common/make-pagination-query.js"; - -export const meta = { - tags: ["users", "gallery"], - requireCredentialPrivateMode: true, - - description: "Show all gallery posts by the given user.", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "GalleryPost", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = makePaginationQuery( - GalleryPosts.createQueryBuilder("post"), - ps.sinceId, - ps.untilId, - ).andWhere("post.userId = :userId", { userId: ps.userId }); - - const posts = await query.take(ps.limit).getMany(); - - return await GalleryPosts.packMany(posts, user); -}); diff --git a/packages/backend/src/server/api/endpoints/users/get-frequently-replied-users.ts b/packages/backend/src/server/api/endpoints/users/get-frequently-replied-users.ts deleted file mode 100644 index 9722804c8d..0000000000 --- a/packages/backend/src/server/api/endpoints/users/get-frequently-replied-users.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { Not, In, IsNull } from "typeorm"; -import { maximum } from "@/prelude/array.js"; -import { Notes, Users } from "@/models/index.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { getUser } from "../../common/getters.js"; - -export const meta = { - tags: ["users"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - description: - "Get a list of other users that the specified user frequently replies to.", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - properties: { - user: { - type: "object", - optional: false, - nullable: false, - ref: "UserDetailed", - }, - weight: { - type: "number", - optional: false, - nullable: false, - }, - }, - }, - }, - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "e6965129-7b2a-40a4-bae2-cd84cd434822", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - // Lookup user - const user = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - // Fetch recent notes - const recentNotes = await Notes.find({ - where: { - userId: user.id, - replyId: Not(IsNull()), - }, - order: { - id: -1, - }, - take: 1000, - select: ["replyId"], - }); - - // 投稿が少なかったら中断 - if (recentNotes.length === 0) { - return []; - } - - // TODO ミュートを考慮 - const replyTargetNotes = await Notes.find({ - where: { - id: In(recentNotes.map((p) => p.replyId)), - }, - select: ["userId"], - }); - - const repliedUsers: any = {}; - - // Extract replies from recent notes - for (const userId of replyTargetNotes.map((x) => x.userId.toString())) { - if (repliedUsers[userId]) { - repliedUsers[userId]++; - } else { - repliedUsers[userId] = 1; - } - } - - // Calc peak - const peak = maximum(Object.values(repliedUsers)); - - // Sort replies by frequency - const repliedUsersSorted = Object.keys(repliedUsers).sort( - (a, b) => repliedUsers[b] - repliedUsers[a], - ); - - // Extract top replied users - const topRepliedUsers = repliedUsersSorted.slice(0, ps.limit); - - // Make replies object (includes weights) - const repliesObj = await Promise.all( - topRepliedUsers.map(async (user) => ({ - user: await Users.pack(user, me, { detail: true }), - weight: repliedUsers[user] / peak, - })), - ); - - return repliesObj; -}); diff --git a/packages/backend/src/server/api/endpoints/users/groups/create.ts b/packages/backend/src/server/api/endpoints/users/groups/create.ts deleted file mode 100644 index 76bd78c49f..0000000000 --- a/packages/backend/src/server/api/endpoints/users/groups/create.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { UserGroups, UserGroupJoinings } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import type { UserGroup } from "@/models/entities/user-group.js"; -import type { UserGroupJoining } from "@/models/entities/user-group-joining.js"; -import define from "../../../define.js"; - -export const meta = { - tags: ["groups"], - - requireCredential: true, - - kind: "write:user-groups", - - description: "Create a new group.", - - res: { - type: "object", - optional: false, - nullable: false, - ref: "UserGroup", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - name: { type: "string", minLength: 1, maxLength: 100 }, - }, - required: ["name"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const userGroup = await UserGroups.insert({ - id: genId(), - createdAt: new Date(), - userId: user.id, - name: ps.name, - } as UserGroup).then((x) => UserGroups.findOneByOrFail(x.identifiers[0])); - - // Push the owner - await UserGroupJoinings.insert({ - id: genId(), - createdAt: new Date(), - userId: user.id, - userGroupId: userGroup.id, - } as UserGroupJoining); - - return await UserGroups.pack(userGroup); -}); diff --git a/packages/backend/src/server/api/endpoints/users/groups/delete.ts b/packages/backend/src/server/api/endpoints/users/groups/delete.ts deleted file mode 100644 index 81c15ad38e..0000000000 --- a/packages/backend/src/server/api/endpoints/users/groups/delete.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { UserGroups } from "@/models/index.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["groups"], - - requireCredential: true, - - kind: "write:user-groups", - - description: "Delete an existing group.", - - errors: { - noSuchGroup: { - message: "No such group.", - code: "NO_SUCH_GROUP", - id: "63dbd64c-cd77-413f-8e08-61781e210b38", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - groupId: { type: "string", format: "misskey:id" }, - }, - required: ["groupId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const userGroup = await UserGroups.findOneBy({ - id: ps.groupId, - userId: user.id, - }); - - if (userGroup == null) { - throw new ApiError(meta.errors.noSuchGroup); - } - - await UserGroups.delete(userGroup.id); -}); diff --git a/packages/backend/src/server/api/endpoints/users/groups/invitations/accept.ts b/packages/backend/src/server/api/endpoints/users/groups/invitations/accept.ts deleted file mode 100644 index 5cb3a7bad3..0000000000 --- a/packages/backend/src/server/api/endpoints/users/groups/invitations/accept.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { UserGroupJoinings, UserGroupInvitations } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import type { UserGroupJoining } from "@/models/entities/user-group-joining.js"; -import { ApiError } from "../../../../error.js"; -import define from "../../../../define.js"; - -export const meta = { - tags: ["groups", "users"], - - requireCredential: true, - - kind: "write:user-groups", - - description: "Join a group the authenticated user has been invited to.", - - errors: { - noSuchInvitation: { - message: "No such invitation.", - code: "NO_SUCH_INVITATION", - id: "98c11eca-c890-4f42-9806-c8c8303ebb5e", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - invitationId: { type: "string", format: "misskey:id" }, - }, - required: ["invitationId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Fetch the invitation - const invitation = await UserGroupInvitations.findOneBy({ - id: ps.invitationId, - }); - - if (invitation == null) { - throw new ApiError(meta.errors.noSuchInvitation); - } - - if (invitation.userId !== user.id) { - throw new ApiError(meta.errors.noSuchInvitation); - } - - // Push the user - await UserGroupJoinings.insert({ - id: genId(), - createdAt: new Date(), - userId: user.id, - userGroupId: invitation.userGroupId, - } as UserGroupJoining); - - UserGroupInvitations.delete(invitation.id); -}); diff --git a/packages/backend/src/server/api/endpoints/users/groups/invitations/reject.ts b/packages/backend/src/server/api/endpoints/users/groups/invitations/reject.ts deleted file mode 100644 index c04ebed23b..0000000000 --- a/packages/backend/src/server/api/endpoints/users/groups/invitations/reject.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { UserGroupInvitations } from "@/models/index.js"; -import define from "../../../../define.js"; -import { ApiError } from "../../../../error.js"; - -export const meta = { - tags: ["groups", "users"], - - requireCredential: true, - - kind: "write:user-groups", - - description: - "Delete an existing group invitation for the authenticated user without joining the group.", - - errors: { - noSuchInvitation: { - message: "No such invitation.", - code: "NO_SUCH_INVITATION", - id: "ad7471d4-2cd9-44b4-ac68-e7136b4ce656", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - invitationId: { type: "string", format: "misskey:id" }, - }, - required: ["invitationId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Fetch the invitation - const invitation = await UserGroupInvitations.findOneBy({ - id: ps.invitationId, - }); - - if (invitation == null) { - throw new ApiError(meta.errors.noSuchInvitation); - } - - if (invitation.userId !== user.id) { - throw new ApiError(meta.errors.noSuchInvitation); - } - - await UserGroupInvitations.delete(invitation.id); -}); diff --git a/packages/backend/src/server/api/endpoints/users/groups/invite.ts b/packages/backend/src/server/api/endpoints/users/groups/invite.ts deleted file mode 100644 index 10cc215861..0000000000 --- a/packages/backend/src/server/api/endpoints/users/groups/invite.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { - UserGroups, - UserGroupJoinings, - UserGroupInvitations, -} from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import type { UserGroupInvitation } from "@/models/entities/user-group-invitation.js"; -import { createNotification } from "@/services/create-notification.js"; -import { getUser } from "../../../common/getters.js"; -import { ApiError } from "../../../error.js"; -import define from "../../../define.js"; - -export const meta = { - tags: ["groups", "users"], - - requireCredential: true, - - kind: "write:user-groups", - - description: "Invite a user to an existing group.", - - errors: { - noSuchGroup: { - message: "No such group.", - code: "NO_SUCH_GROUP", - id: "583f8bc0-8eee-4b78-9299-1e14fc91e409", - }, - - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "da52de61-002c-475b-90e1-ba64f9cf13a8", - }, - - alreadyAdded: { - message: "That user has already been added to that group.", - code: "ALREADY_ADDED", - id: "7e35c6a0-39b2-4488-aea6-6ee20bd5da2c", - }, - - alreadyInvited: { - message: "That user has already been invited to that group.", - code: "ALREADY_INVITED", - id: "ee0f58b4-b529-4d13-b761-b9a3e69f97e6", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - groupId: { type: "string", format: "misskey:id" }, - userId: { type: "string", format: "misskey:id" }, - }, - required: ["groupId", "userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - // Fetch the group - const userGroup = await UserGroups.findOneBy({ - id: ps.groupId, - userId: me.id, - }); - - if (userGroup == null) { - throw new ApiError(meta.errors.noSuchGroup); - } - - // Fetch the user - const user = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - const joining = await UserGroupJoinings.findOneBy({ - userGroupId: userGroup.id, - userId: user.id, - }); - - if (joining) { - throw new ApiError(meta.errors.alreadyAdded); - } - - const existInvitation = await UserGroupInvitations.findOneBy({ - userGroupId: userGroup.id, - userId: user.id, - }); - - if (existInvitation) { - throw new ApiError(meta.errors.alreadyInvited); - } - - const invitation = await UserGroupInvitations.insert({ - id: genId(), - createdAt: new Date(), - userId: user.id, - userGroupId: userGroup.id, - } as UserGroupInvitation).then((x) => - UserGroupInvitations.findOneByOrFail(x.identifiers[0]), - ); - - // 通知を作成 - createNotification(user.id, "groupInvited", { - notifierId: me.id, - userGroupInvitationId: invitation.id, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/users/groups/joined.ts b/packages/backend/src/server/api/endpoints/users/groups/joined.ts deleted file mode 100644 index 8422cf586d..0000000000 --- a/packages/backend/src/server/api/endpoints/users/groups/joined.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { Not, In } from "typeorm"; -import { UserGroups, UserGroupJoinings } from "@/models/index.js"; -import define from "../../../define.js"; - -export const meta = { - tags: ["groups", "account"], - - requireCredential: true, - - kind: "read:user-groups", - - description: "List the groups that the authenticated user is a member of.", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "UserGroup", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const ownedGroups = await UserGroups.findBy({ - userId: me.id, - }); - - const joinings = await UserGroupJoinings.findBy({ - userId: me.id, - ...(ownedGroups.length > 0 - ? { - userGroupId: Not(In(ownedGroups.map((x) => x.id))), - } - : {}), - }); - - return await Promise.all(joinings.map((x) => UserGroups.pack(x.userGroupId))); -}); diff --git a/packages/backend/src/server/api/endpoints/users/groups/leave.ts b/packages/backend/src/server/api/endpoints/users/groups/leave.ts deleted file mode 100644 index d963b1826e..0000000000 --- a/packages/backend/src/server/api/endpoints/users/groups/leave.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { UserGroups, UserGroupJoinings } from "@/models/index.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["groups", "users"], - - requireCredential: true, - - kind: "write:user-groups", - - description: - "Leave a group. The owner of a group can not leave. They must transfer ownership or delete the group instead.", - - errors: { - noSuchGroup: { - message: "No such group.", - code: "NO_SUCH_GROUP", - id: "62780270-1f67-5dc0-daca-3eb510612e31", - }, - - youAreOwner: { - message: "Your are the owner.", - code: "YOU_ARE_OWNER", - id: "b6d6e0c2-ef8a-9bb8-653d-79f4a3107c69", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - groupId: { type: "string", format: "misskey:id" }, - }, - required: ["groupId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - // Fetch the group - const userGroup = await UserGroups.findOneBy({ - id: ps.groupId, - }); - - if (userGroup == null) { - throw new ApiError(meta.errors.noSuchGroup); - } - - if (me.id === userGroup.userId) { - throw new ApiError(meta.errors.youAreOwner); - } - - await UserGroupJoinings.delete({ userGroupId: userGroup.id, userId: me.id }); -}); diff --git a/packages/backend/src/server/api/endpoints/users/groups/owned.ts b/packages/backend/src/server/api/endpoints/users/groups/owned.ts deleted file mode 100644 index d86185ff02..0000000000 --- a/packages/backend/src/server/api/endpoints/users/groups/owned.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { UserGroups } from "@/models/index.js"; -import define from "../../../define.js"; - -export const meta = { - tags: ["groups", "account"], - - requireCredential: true, - - kind: "read:user-groups", - - description: "List the groups that the authenticated user is the owner of.", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "UserGroup", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const userGroups = await UserGroups.findBy({ - userId: me.id, - }); - - return await Promise.all(userGroups.map((x) => UserGroups.pack(x))); -}); diff --git a/packages/backend/src/server/api/endpoints/users/groups/pull.ts b/packages/backend/src/server/api/endpoints/users/groups/pull.ts deleted file mode 100644 index 1f79a2d2b7..0000000000 --- a/packages/backend/src/server/api/endpoints/users/groups/pull.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { UserGroups, UserGroupJoinings } from "@/models/index.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { getUser } from "../../../common/getters.js"; - -export const meta = { - tags: ["groups", "users"], - - requireCredential: true, - - kind: "write:user-groups", - - description: - "Removes a specified user from a group. The owner can not be removed.", - - errors: { - noSuchGroup: { - message: "No such group.", - code: "NO_SUCH_GROUP", - id: "4662487c-05b1-4b78-86e5-fd46998aba74", - }, - - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "0b5cc374-3681-41da-861e-8bc1146f7a55", - }, - - isOwner: { - message: "The user is the owner.", - code: "IS_OWNER", - id: "1546eed5-4414-4dea-81c1-b0aec4f6d2af", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - groupId: { type: "string", format: "misskey:id" }, - userId: { type: "string", format: "misskey:id" }, - }, - required: ["groupId", "userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - // Fetch the group - const userGroup = await UserGroups.findOneBy({ - id: ps.groupId, - userId: me.id, - }); - - if (userGroup == null) { - throw new ApiError(meta.errors.noSuchGroup); - } - - // Fetch the user - const user = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - if (user.id === userGroup.userId) { - throw new ApiError(meta.errors.isOwner); - } - - // Pull the user - await UserGroupJoinings.delete({ - userGroupId: userGroup.id, - userId: user.id, - }); -}); diff --git a/packages/backend/src/server/api/endpoints/users/groups/show.ts b/packages/backend/src/server/api/endpoints/users/groups/show.ts deleted file mode 100644 index 46f4410c84..0000000000 --- a/packages/backend/src/server/api/endpoints/users/groups/show.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { UserGroups, UserGroupJoinings } from "@/models/index.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["groups", "account"], - - requireCredential: true, - - kind: "read:user-groups", - - description: "Show the properties of a group.", - - res: { - type: "object", - optional: false, - nullable: false, - ref: "UserGroup", - }, - - errors: { - noSuchGroup: { - message: "No such group.", - code: "NO_SUCH_GROUP", - id: "ea04751e-9b7e-487b-a509-330fb6bd6b9b", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - groupId: { type: "string", format: "misskey:id" }, - }, - required: ["groupId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - // Fetch the group - const userGroup = await UserGroups.findOneBy({ - id: ps.groupId, - }); - - if (userGroup == null) { - throw new ApiError(meta.errors.noSuchGroup); - } - - const joining = await UserGroupJoinings.findOneBy({ - userId: me.id, - userGroupId: userGroup.id, - }); - - if (joining == null && userGroup.userId !== me.id) { - throw new ApiError(meta.errors.noSuchGroup); - } - - return await UserGroups.pack(userGroup); -}); diff --git a/packages/backend/src/server/api/endpoints/users/groups/transfer.ts b/packages/backend/src/server/api/endpoints/users/groups/transfer.ts deleted file mode 100644 index 0322441574..0000000000 --- a/packages/backend/src/server/api/endpoints/users/groups/transfer.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { UserGroups, UserGroupJoinings } from "@/models/index.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { getUser } from "../../../common/getters.js"; - -export const meta = { - tags: ["groups", "users"], - - requireCredential: true, - - kind: "write:user-groups", - - description: - "Transfer ownership of a group from the authenticated user to another user.", - - res: { - type: "object", - optional: false, - nullable: false, - ref: "UserGroup", - }, - - errors: { - noSuchGroup: { - message: "No such group.", - code: "NO_SUCH_GROUP", - id: "8e31d36b-2f88-4ccd-a438-e2d78a9162db", - }, - - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "711f7ebb-bbb9-4dfa-b540-b27809fed5e9", - }, - - noSuchGroupMember: { - message: "No such group member.", - code: "NO_SUCH_GROUP_MEMBER", - id: "d31bebee-196d-42c2-9a3e-9474d4be6cc4", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - groupId: { type: "string", format: "misskey:id" }, - userId: { type: "string", format: "misskey:id" }, - }, - required: ["groupId", "userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - // Fetch the group - const userGroup = await UserGroups.findOneBy({ - id: ps.groupId, - userId: me.id, - }); - - if (userGroup == null) { - throw new ApiError(meta.errors.noSuchGroup); - } - - // Fetch the user - const user = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - const joining = await UserGroupJoinings.findOneBy({ - userGroupId: userGroup.id, - userId: user.id, - }); - - if (joining == null) { - throw new ApiError(meta.errors.noSuchGroupMember); - } - - await UserGroups.update(userGroup.id, { - userId: ps.userId, - }); - - return await UserGroups.pack(userGroup.id); -}); diff --git a/packages/backend/src/server/api/endpoints/users/groups/update.ts b/packages/backend/src/server/api/endpoints/users/groups/update.ts deleted file mode 100644 index fa720c9c45..0000000000 --- a/packages/backend/src/server/api/endpoints/users/groups/update.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { UserGroups } from "@/models/index.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["groups"], - - requireCredential: true, - - kind: "write:user-groups", - - description: "Update the properties of a group.", - - res: { - type: "object", - optional: false, - nullable: false, - ref: "UserGroup", - }, - - errors: { - noSuchGroup: { - message: "No such group.", - code: "NO_SUCH_GROUP", - id: "9081cda3-7a9e-4fac-a6ce-908d70f282f6", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - groupId: { type: "string", format: "misskey:id" }, - name: { type: "string", minLength: 1, maxLength: 100 }, - }, - required: ["groupId", "name"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - // Fetch the group - const userGroup = await UserGroups.findOneBy({ - id: ps.groupId, - userId: me.id, - }); - - if (userGroup == null) { - throw new ApiError(meta.errors.noSuchGroup); - } - - await UserGroups.update(userGroup.id, { - name: ps.name, - }); - - return await UserGroups.pack(userGroup.id); -}); diff --git a/packages/backend/src/server/api/endpoints/users/lists/create.ts b/packages/backend/src/server/api/endpoints/users/lists/create.ts deleted file mode 100644 index 6bbbf603e5..0000000000 --- a/packages/backend/src/server/api/endpoints/users/lists/create.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { UserLists } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import type { UserList } from "@/models/entities/user-list.js"; -import define from "../../../define.js"; - -export const meta = { - tags: ["lists"], - - requireCredential: true, - - kind: "write:account", - - description: "Create a new list of users.", - - res: { - type: "object", - optional: false, - nullable: false, - ref: "UserList", - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - name: { type: "string", minLength: 1, maxLength: 100 }, - }, - required: ["name"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const userList = await UserLists.insert({ - id: genId(), - createdAt: new Date(), - userId: user.id, - name: ps.name, - } as UserList).then((x) => UserLists.findOneByOrFail(x.identifiers[0])); - - return await UserLists.pack(userList); -}); diff --git a/packages/backend/src/server/api/endpoints/users/lists/delete-all.ts b/packages/backend/src/server/api/endpoints/users/lists/delete-all.ts deleted file mode 100644 index 49c4cf6f63..0000000000 --- a/packages/backend/src/server/api/endpoints/users/lists/delete-all.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { UserLists } from "@/models/index.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["lists"], - - requireCredential: true, - - kind: "write:account", - - description: "Delete all lists of users.", - - errors: { - noSuchList: { - message: "No such list.", - code: "NO_SUCH_LIST", - id: "78436795-db79-42f5-b1e2-55ea2cf19166", - }, - }, -} as const; - -export const paramDef = { - type: "object", -} as const; - -export default define(meta, paramDef, async (ps, user) => { - while ((await UserLists.findOneBy({ userId: user.id })) != null) { - const userList = await UserLists.findOneBy({ userId: user.id }); - if (userList == null) { - throw new ApiError(meta.errors.noSuchList); - } - await UserLists.delete(userList.id); - } -}); diff --git a/packages/backend/src/server/api/endpoints/users/lists/delete.ts b/packages/backend/src/server/api/endpoints/users/lists/delete.ts deleted file mode 100644 index 4566295676..0000000000 --- a/packages/backend/src/server/api/endpoints/users/lists/delete.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { UserLists } from "@/models/index.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["lists"], - - requireCredential: true, - - kind: "write:account", - - description: "Delete an existing list of users.", - - errors: { - noSuchList: { - message: "No such list.", - code: "NO_SUCH_LIST", - id: "78436795-db79-42f5-b1e2-55ea2cf19166", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - listId: { type: "string", format: "misskey:id" }, - }, - required: ["listId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const userList = await UserLists.findOneBy({ - id: ps.listId, - userId: user.id, - }); - - if (userList == null) { - throw new ApiError(meta.errors.noSuchList); - } - - await UserLists.delete(userList.id); -}); diff --git a/packages/backend/src/server/api/endpoints/users/lists/list.ts b/packages/backend/src/server/api/endpoints/users/lists/list.ts deleted file mode 100644 index 5d590ee0ec..0000000000 --- a/packages/backend/src/server/api/endpoints/users/lists/list.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { UserLists } from "@/models/index.js"; -import define from "../../../define.js"; - -export const meta = { - tags: ["lists", "account"], - - requireCredential: true, - - kind: "read:account", - - description: "Show all lists that the authenticated user has created.", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "UserList", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: {}, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const userLists = await UserLists.findBy({ - userId: me.id, - }); - - return await Promise.all(userLists.map((x) => UserLists.pack(x))); -}); diff --git a/packages/backend/src/server/api/endpoints/users/lists/pull.ts b/packages/backend/src/server/api/endpoints/users/lists/pull.ts deleted file mode 100644 index 07fae20675..0000000000 --- a/packages/backend/src/server/api/endpoints/users/lists/pull.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { publishUserListStream } from "@/services/stream.js"; -import { UserLists, UserListJoinings, Users } from "@/models/index.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { getUser } from "../../../common/getters.js"; - -export const meta = { - tags: ["lists", "users"], - - requireCredential: true, - - kind: "write:account", - - description: "Remove a user from a list.", - - errors: { - noSuchList: { - message: "No such list.", - code: "NO_SUCH_LIST", - id: "7f44670e-ab16-43b8-b4c1-ccd2ee89cc02", - }, - - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "588e7f72-c744-4a61-b180-d354e912bda2", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - listId: { type: "string", format: "misskey:id" }, - userId: { type: "string", format: "misskey:id" }, - }, - required: ["listId", "userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - // Fetch the list - const userList = await UserLists.findOneBy({ - id: ps.listId, - userId: me.id, - }); - - if (userList == null) { - throw new ApiError(meta.errors.noSuchList); - } - - // Fetch the user - const user = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - // Pull the user - await UserListJoinings.delete({ userListId: userList.id, userId: user.id }); - - publishUserListStream(userList.id, "userRemoved", await Users.pack(user)); -}); diff --git a/packages/backend/src/server/api/endpoints/users/lists/push.ts b/packages/backend/src/server/api/endpoints/users/lists/push.ts deleted file mode 100644 index a14195bbc3..0000000000 --- a/packages/backend/src/server/api/endpoints/users/lists/push.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { pushUserToUserList } from "@/services/user-list/push.js"; -import { UserLists, UserListJoinings, Blockings } from "@/models/index.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; -import { getUser } from "../../../common/getters.js"; - -export const meta = { - tags: ["lists", "users"], - - requireCredential: true, - - kind: "write:account", - - description: "Add a user to an existing list.", - - errors: { - noSuchList: { - message: "No such list.", - code: "NO_SUCH_LIST", - id: "2214501d-ac96-4049-b717-91e42272a711", - }, - - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "a89abd3d-f0bc-4cce-beb1-2f446f4f1e6a", - }, - - alreadyAdded: { - message: "That user has already been added to that list.", - code: "ALREADY_ADDED", - id: "1de7c884-1595-49e9-857e-61f12f4d4fc5", - }, - - youHaveBeenBlocked: { - message: - "You cannot push this user because you have been blocked by this user.", - code: "YOU_HAVE_BEEN_BLOCKED", - id: "990232c5-3f9d-4d83-9f3f-ef27b6332a4b", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - listId: { type: "string", format: "misskey:id" }, - userId: { type: "string", format: "misskey:id" }, - }, - required: ["listId", "userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - // Fetch the list - const userList = await UserLists.findOneBy({ - id: ps.listId, - userId: me.id, - }); - - if (userList == null) { - throw new ApiError(meta.errors.noSuchList); - } - - // Fetch the user - const user = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - // Check blocking - if (user.id !== me.id) { - const block = await Blockings.findOneBy({ - blockerId: user.id, - blockeeId: me.id, - }); - if (block) { - throw new ApiError(meta.errors.youHaveBeenBlocked); - } - } - - const exist = await UserListJoinings.findOneBy({ - userListId: userList.id, - userId: user.id, - }); - - if (exist) { - throw new ApiError(meta.errors.alreadyAdded); - } - - // Push the user - await pushUserToUserList(user, userList); -}); diff --git a/packages/backend/src/server/api/endpoints/users/lists/show.ts b/packages/backend/src/server/api/endpoints/users/lists/show.ts deleted file mode 100644 index 716fd405dc..0000000000 --- a/packages/backend/src/server/api/endpoints/users/lists/show.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { UserLists } from "@/models/index.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["lists", "account"], - - requireCredential: true, - - kind: "read:account", - - description: "Show the properties of a list.", - - res: { - type: "object", - optional: false, - nullable: false, - ref: "UserList", - }, - - errors: { - noSuchList: { - message: "No such list.", - code: "NO_SUCH_LIST", - id: "7bc05c21-1d7a-41ae-88f1-66820f4dc686", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - listId: { type: "string", format: "misskey:id" }, - }, - required: ["listId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - // Fetch the list - const userList = await UserLists.findOneBy({ - id: ps.listId, - userId: me.id, - }); - - if (userList == null) { - throw new ApiError(meta.errors.noSuchList); - } - - return await UserLists.pack(userList); -}); diff --git a/packages/backend/src/server/api/endpoints/users/lists/update.ts b/packages/backend/src/server/api/endpoints/users/lists/update.ts deleted file mode 100644 index 0ac788fd37..0000000000 --- a/packages/backend/src/server/api/endpoints/users/lists/update.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { UserLists } from "@/models/index.js"; -import define from "../../../define.js"; -import { ApiError } from "../../../error.js"; - -export const meta = { - tags: ["lists"], - - requireCredential: true, - - kind: "write:account", - - description: "Update the properties of a list.", - - res: { - type: "object", - optional: false, - nullable: false, - ref: "UserList", - }, - - errors: { - noSuchList: { - message: "No such list.", - code: "NO_SUCH_LIST", - id: "796666fe-3dff-4d39-becb-8a5932c1d5b7", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - listId: { type: "string", format: "misskey:id" }, - name: { type: "string", minLength: 1, maxLength: 100 }, - }, - required: ["listId", "name"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - // Fetch the list - const userList = await UserLists.findOneBy({ - id: ps.listId, - userId: user.id, - }); - - if (userList == null) { - throw new ApiError(meta.errors.noSuchList); - } - - await UserLists.update(userList.id, { - name: ps.name, - }); - - return await UserLists.pack(userList.id); -}); diff --git a/packages/backend/src/server/api/endpoints/users/notes.ts b/packages/backend/src/server/api/endpoints/users/notes.ts deleted file mode 100644 index 724cfc9af1..0000000000 --- a/packages/backend/src/server/api/endpoints/users/notes.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { Brackets } from "typeorm"; -import { Notes } from "@/models/index.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; -import { getUser } from "../../common/getters.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { generateVisibilityQuery } from "../../common/generate-visibility-query.js"; -import { generateMutedUserQuery } from "../../common/generate-muted-user-query.js"; -import { generateBlockedUserQuery } from "../../common/generate-block-query.js"; - -export const meta = { - tags: ["users", "notes"], - - requireCredentialPrivateMode: true, - description: "Show all notes that this user created.", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Note", - }, - }, - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "27e494ba-2ac2-48e8-893b-10d4d8c2387b", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - includeReplies: { type: "boolean", default: true }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - sinceDate: { type: "integer" }, - untilDate: { type: "integer" }, - includeMyRenotes: { type: "boolean", default: true }, - withFiles: { type: "boolean", default: false }, - fileType: { - type: "array", - items: { - type: "string", - }, - }, - excludeNsfw: { type: "boolean", default: false }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - // Lookup user - const user = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - //#region Construct query - const query = makePaginationQuery( - Notes.createQueryBuilder("note"), - ps.sinceId, - ps.untilId, - ps.sinceDate, - ps.untilDate, - ) - .andWhere("note.userId = :userId", { userId: user.id }) - .innerJoinAndSelect("note.user", "user") - .leftJoinAndSelect("user.avatar", "avatar") - .leftJoinAndSelect("user.banner", "banner") - .leftJoinAndSelect("note.reply", "reply") - .leftJoinAndSelect("note.renote", "renote") - .leftJoinAndSelect("reply.user", "replyUser") - .leftJoinAndSelect("replyUser.avatar", "replyUserAvatar") - .leftJoinAndSelect("replyUser.banner", "replyUserBanner") - .leftJoinAndSelect("renote.user", "renoteUser") - .leftJoinAndSelect("renoteUser.avatar", "renoteUserAvatar") - .leftJoinAndSelect("renoteUser.banner", "renoteUserBanner"); - - generateVisibilityQuery(query, me); - if (me) { - generateMutedUserQuery(query, me, user); - generateBlockedUserQuery(query, me); - } - - if (ps.withFiles) { - query.andWhere("note.fileIds != '{}'"); - } - - if (ps.fileType != null) { - query.andWhere("note.fileIds != '{}'"); - query.andWhere( - new Brackets((qb) => { - for (const type of ps.fileType!) { - const i = ps.fileType!.indexOf(type); - qb.orWhere(`:type${i} = ANY(note.attachedFileTypes)`, { - [`type${i}`]: type, - }); - } - }), - ); - - if (ps.excludeNsfw) { - query.andWhere("note.cw IS NULL"); - query.andWhere( - '0 = (SELECT COUNT(*) FROM drive_file df WHERE df.id = ANY(note."fileIds") AND df."isSensitive" = TRUE)', - ); - } - } - - if (!ps.includeReplies) { - query.andWhere("note.replyId IS NULL"); - } - - if (ps.includeMyRenotes === false) { - query.andWhere( - new Brackets((qb) => { - qb.orWhere("note.userId != :userId", { userId: user.id }); - qb.orWhere("note.renoteId IS NULL"); - qb.orWhere("note.text IS NOT NULL"); - qb.orWhere("note.fileIds != '{}'"); - qb.orWhere( - '0 < (SELECT COUNT(*) FROM poll WHERE poll."noteId" = note.id)', - ); - }), - ); - } - - //#endregion - - const timeline = await query.take(ps.limit).getMany(); - - return await Notes.packMany(timeline, me); -}); diff --git a/packages/backend/src/server/api/endpoints/users/pages.ts b/packages/backend/src/server/api/endpoints/users/pages.ts deleted file mode 100644 index c08258b19d..0000000000 --- a/packages/backend/src/server/api/endpoints/users/pages.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { Pages } from "@/models/index.js"; -import define from "../../define.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; - -export const meta = { - tags: ["users", "pages"], - requireCredentialPrivateMode: true, - - description: "Show all pages this user created.", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "Page", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, user) => { - const query = makePaginationQuery( - Pages.createQueryBuilder("page"), - ps.sinceId, - ps.untilId, - ) - .andWhere("page.userId = :userId", { userId: ps.userId }) - .andWhere("page.visibility = 'public'") - .andWhere("page.isPublic = true"); - - const pages = await query.take(ps.limit).getMany(); - - return await Pages.packMany(pages); -}); diff --git a/packages/backend/src/server/api/endpoints/users/reactions.ts b/packages/backend/src/server/api/endpoints/users/reactions.ts deleted file mode 100644 index 17b7a04a06..0000000000 --- a/packages/backend/src/server/api/endpoints/users/reactions.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { NoteReactions, UserProfiles } from "@/models/index.js"; -import define from "../../define.js"; -import { makePaginationQuery } from "../../common/make-pagination-query.js"; -import { generateVisibilityQuery } from "../../common/generate-visibility-query.js"; -import { ApiError } from "../../error.js"; - -export const meta = { - tags: ["users", "reactions"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - description: "Show all reactions this user made.", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "NoteReaction", - }, - }, - - errors: { - reactionsNotPublic: { - message: "Reactions of the user is not public.", - code: "REACTIONS_NOT_PUBLIC", - id: "673a7dd2-6924-1093-e0c0-e68456ceae5c", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - sinceId: { type: "string", format: "misskey:id" }, - untilId: { type: "string", format: "misskey:id" }, - sinceDate: { type: "integer" }, - untilDate: { type: "integer" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const profile = await UserProfiles.findOneByOrFail({ userId: ps.userId }); - - if (me == null || (me.id !== ps.userId && !profile.publicReactions)) { - throw new ApiError(meta.errors.reactionsNotPublic); - } - - const query = makePaginationQuery( - NoteReactions.createQueryBuilder("reaction"), - ps.sinceId, - ps.untilId, - ps.sinceDate, - ps.untilDate, - ) - .andWhere("reaction.userId = :userId", { userId: ps.userId }) - .leftJoinAndSelect("reaction.note", "note"); - - generateVisibilityQuery(query, me); - - const reactions = await query.take(ps.limit).getMany(); - - return await NoteReactions.packMany(reactions, me, { withNote: true }); -}); diff --git a/packages/backend/src/server/api/endpoints/users/recommendation.ts b/packages/backend/src/server/api/endpoints/users/recommendation.ts deleted file mode 100644 index 615cca7856..0000000000 --- a/packages/backend/src/server/api/endpoints/users/recommendation.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { Users, Followings } from "@/models/index.js"; -import define from "../../define.js"; -import { generateMutedUserQueryForUsers } from "../../common/generate-muted-user-query.js"; -import { - generateBlockedUserQuery, - generateBlockQueryForUsers, -} from "../../common/generate-block-query.js"; -import { DAY } from "@/const.js"; - -export const meta = { - tags: ["users"], - - requireCredential: true, - - kind: "read:account", - - description: - "Show users that the authenticated user might be interested to follow.", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "UserDetailed", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - offset: { type: "integer", default: 0 }, - }, - required: [], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const query = Users.createQueryBuilder("user") - .where("user.isLocked = FALSE") - .andWhere("user.isExplorable = TRUE") - .andWhere("user.host IS NULL") - .andWhere("user.updatedAt >= :date", { - date: new Date(Date.now() - 7 * DAY), - }) - .andWhere("user.id != :meId", { meId: me.id }) - .orderBy("user.followersCount", "DESC"); - - generateMutedUserQueryForUsers(query, me); - generateBlockQueryForUsers(query, me); - generateBlockedUserQuery(query, me); - - const followingQuery = Followings.createQueryBuilder("following") - .select("following.followeeId") - .where("following.followerId = :followerId", { followerId: me.id }); - - query.andWhere(`user.id NOT IN (${followingQuery.getQuery()})`); - - query.setParameters(followingQuery.getParameters()); - - const users = await query.take(ps.limit).skip(ps.offset).getMany(); - - return await Users.packMany(users, me, { detail: true }); -}); diff --git a/packages/backend/src/server/api/endpoints/users/relation.ts b/packages/backend/src/server/api/endpoints/users/relation.ts deleted file mode 100644 index 5580eaea0b..0000000000 --- a/packages/backend/src/server/api/endpoints/users/relation.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { Users } from "@/models/index.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["users"], - - requireCredential: true, - - description: - "Show the different kinds of relations between the authenticated user and the specified user(s).", - - res: { - optional: false, - nullable: false, - oneOf: [ - { - type: "object", - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - isFollowing: { - type: "boolean", - optional: false, - nullable: false, - }, - hasPendingFollowRequestFromYou: { - type: "boolean", - optional: false, - nullable: false, - }, - hasPendingFollowRequestToYou: { - type: "boolean", - optional: false, - nullable: false, - }, - isFollowed: { - type: "boolean", - optional: false, - nullable: false, - }, - isBlocking: { - type: "boolean", - optional: false, - nullable: false, - }, - isBlocked: { - type: "boolean", - optional: false, - nullable: false, - }, - isMuted: { - type: "boolean", - optional: false, - nullable: false, - }, - isRenoteMuted: { - type: "boolean", - optional: false, - nullable: false, - }, - }, - }, - { - type: "array", - items: { - type: "object", - optional: false, - nullable: false, - properties: { - id: { - type: "string", - optional: false, - nullable: false, - format: "id", - }, - isFollowing: { - type: "boolean", - optional: false, - nullable: false, - }, - hasPendingFollowRequestFromYou: { - type: "boolean", - optional: false, - nullable: false, - }, - hasPendingFollowRequestToYou: { - type: "boolean", - optional: false, - nullable: false, - }, - isFollowed: { - type: "boolean", - optional: false, - nullable: false, - }, - isBlocking: { - type: "boolean", - optional: false, - nullable: false, - }, - isBlocked: { - type: "boolean", - optional: false, - nullable: false, - }, - isMuted: { - type: "boolean", - optional: false, - nullable: false, - }, - isRenoteMuted: { - type: "boolean", - optional: false, - nullable: false, - }, - }, - }, - }, - ], - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { - anyOf: [ - { type: "string", format: "misskey:id" }, - { - type: "array", - items: { type: "string", format: "misskey:id" }, - }, - ], - }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const ids = Array.isArray(ps.userId) ? ps.userId : [ps.userId]; - - const relations = await Promise.all( - ids.map((id) => Users.getRelation(me.id, id)), - ); - - return Array.isArray(ps.userId) ? relations : relations[0]; -}); diff --git a/packages/backend/src/server/api/endpoints/users/report-abuse.ts b/packages/backend/src/server/api/endpoints/users/report-abuse.ts deleted file mode 100644 index 44d3f9b500..0000000000 --- a/packages/backend/src/server/api/endpoints/users/report-abuse.ts +++ /dev/null @@ -1,106 +0,0 @@ -import * as sanitizeHtml from "sanitize-html"; -import { publishAdminStream } from "@/services/stream.js"; -import { AbuseUserReports, Users } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import { sendEmail } from "@/services/send-email.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { getUser } from "../../common/getters.js"; -import { ApiError } from "../../error.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["users"], - - requireCredential: true, - - description: "File a report.", - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "1acefcb5-0959-43fd-9685-b48305736cb5", - }, - - cannotReportYourself: { - message: "Cannot report yourself.", - code: "CANNOT_REPORT_YOURSELF", - id: "1e13149e-b1e8-43cf-902e-c01dbfcb202f", - }, - - cannotReportAdmin: { - message: "Cannot report the admin.", - code: "CANNOT_REPORT_THE_ADMIN", - id: "35e166f5-05fb-4f87-a2d5-adb42676d48f", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - comment: { type: "string", minLength: 1, maxLength: 2048 }, - }, - required: ["userId", "comment"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - // Lookup user - const user = await getUser(ps.userId).catch((e) => { - if (e.id === "15348ddd-432d-49c2-8a5a-8069753becff") - throw new ApiError(meta.errors.noSuchUser); - throw e; - }); - - if (user.id === me.id) { - throw new ApiError(meta.errors.cannotReportYourself); - } - - if (user.isAdmin) { - throw new ApiError(meta.errors.cannotReportAdmin); - } - - const report = await AbuseUserReports.insert({ - id: genId(), - createdAt: new Date(), - targetUserId: user.id, - targetUserHost: user.host, - reporterId: me.id, - reporterHost: null, - comment: ps.comment, - }).then((x) => AbuseUserReports.findOneByOrFail(x.identifiers[0])); - - // Publish event to moderators - setImmediate(async () => { - const moderators = await Users.find({ - where: [ - { - isAdmin: true, - }, - { - isModerator: true, - }, - ], - }); - - for (const moderator of moderators) { - publishAdminStream(moderator.id, "newAbuseUserReport", { - id: report.id, - targetUserId: report.targetUserId, - reporterId: report.reporterId, - comment: report.comment, - }); - } - - const meta = await fetchMeta(); - if (meta.email) { - sendEmail( - meta.email, - "New abuse report", - sanitizeHtml(ps.comment), - sanitizeHtml(ps.comment), - ); - } - }); -}); diff --git a/packages/backend/src/server/api/endpoints/users/search-by-username-and-host.ts b/packages/backend/src/server/api/endpoints/users/search-by-username-and-host.ts deleted file mode 100644 index 99aa2f1af3..0000000000 --- a/packages/backend/src/server/api/endpoints/users/search-by-username-and-host.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { Brackets } from "typeorm"; -import { Followings, Users } from "@/models/index.js"; -import { USER_ACTIVE_THRESHOLD } from "@/const.js"; -import type { User } from "@/models/entities/user.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["users"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - description: "Search for a user by username and/or host.", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "User", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - username: { type: "string", nullable: true }, - host: { type: "string", nullable: true }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - detail: { type: "boolean", default: true }, - }, - anyOf: [{ required: ["username"] }, { required: ["host"] }], -} as const; - -// TODO: avatar,bannerをJOINしたいけどエラーになる - -export default define(meta, paramDef, async (ps, me) => { - const activeThreshold = new Date(Date.now() - 1000 * 60 * 60 * 24 * 30); // 30日 - - if (ps.host) { - const q = Users.createQueryBuilder("user") - .where("user.isSuspended = FALSE") - .andWhere("user.host LIKE :host", { host: `${ps.host.toLowerCase()}%` }); - - if (ps.username) { - q.andWhere("user.usernameLower LIKE :username", { - username: `${ps.username.toLowerCase()}%`, - }); - } - - q.andWhere("user.updatedAt IS NOT NULL"); - q.orderBy("user.updatedAt", "DESC"); - - const users = await q.take(ps.limit).getMany(); - - return await Users.packMany(users, me, { detail: ps.detail }); - } else if (ps.username) { - let users: User[] = []; - - if (me) { - const followingQuery = Followings.createQueryBuilder("following") - .select("following.followeeId") - .where("following.followerId = :followerId", { followerId: me.id }); - - const query = Users.createQueryBuilder("user") - .where(`user.id IN (${followingQuery.getQuery()})`) - .andWhere("user.id != :meId", { meId: me.id }) - .andWhere("user.isSuspended = FALSE") - .andWhere("user.usernameLower LIKE :username", { - username: `${ps.username.toLowerCase()}%`, - }) - .andWhere( - new Brackets((qb) => { - qb.where("user.updatedAt IS NULL").orWhere( - "user.updatedAt > :activeThreshold", - { activeThreshold: activeThreshold }, - ); - }), - ); - - query.setParameters(followingQuery.getParameters()); - - users = await query - .orderBy("user.usernameLower", "ASC") - .take(ps.limit) - .getMany(); - - if (users.length < ps.limit) { - const otherQuery = await Users.createQueryBuilder("user") - .where(`user.id NOT IN (${followingQuery.getQuery()})`) - .andWhere("user.id != :meId", { meId: me.id }) - .andWhere("user.isSuspended = FALSE") - .andWhere("user.usernameLower LIKE :username", { - username: `${ps.username.toLowerCase()}%`, - }) - .andWhere("user.updatedAt IS NOT NULL"); - - otherQuery.setParameters(followingQuery.getParameters()); - - const otherUsers = await otherQuery - .orderBy("user.updatedAt", "DESC") - .take(ps.limit - users.length) - .getMany(); - - users = users.concat(otherUsers); - } - } else { - users = await Users.createQueryBuilder("user") - .where("user.isSuspended = FALSE") - .andWhere("user.usernameLower LIKE :username", { - username: `${ps.username.toLowerCase()}%`, - }) - .andWhere("user.updatedAt IS NOT NULL") - .orderBy("user.updatedAt", "DESC") - .take(ps.limit - users.length) - .getMany(); - } - - return await Users.packMany(users, me, { detail: !!ps.detail }); - } - - return []; -}); diff --git a/packages/backend/src/server/api/endpoints/users/search.ts b/packages/backend/src/server/api/endpoints/users/search.ts deleted file mode 100644 index db687a1075..0000000000 --- a/packages/backend/src/server/api/endpoints/users/search.ts +++ /dev/null @@ -1,149 +0,0 @@ -import { Brackets } from "typeorm"; -import { UserProfiles, Users } from "@/models/index.js"; -import type { User } from "@/models/entities/user.js"; -import define from "../../define.js"; - -export const meta = { - tags: ["users"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - description: "Search for users.", - - res: { - type: "array", - optional: false, - nullable: false, - items: { - type: "object", - optional: false, - nullable: false, - ref: "User", - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - query: { type: "string" }, - offset: { type: "integer", default: 0 }, - limit: { type: "integer", minimum: 1, maximum: 100, default: 10 }, - origin: { - type: "string", - enum: ["local", "remote", "combined"], - default: "combined", - }, - detail: { type: "boolean", default: true }, - }, - required: ["query"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const activeThreshold = new Date(Date.now() - 1000 * 60 * 60 * 24 * 30); // 30日 - - const isUsername = ps.query.startsWith("@"); - - let users: User[] = []; - - if (isUsername) { - const usernameQuery = Users.createQueryBuilder("user") - .where("user.usernameLower LIKE :username", { - username: `${ps.query.replace("@", "").toLowerCase()}%`, - }) - .andWhere( - new Brackets((qb) => { - qb.where("user.updatedAt IS NULL").orWhere( - "user.updatedAt > :activeThreshold", - { activeThreshold: activeThreshold }, - ); - }), - ) - .andWhere("user.isSuspended = FALSE"); - - if (ps.origin === "local") { - usernameQuery.andWhere("user.host IS NULL"); - } else if (ps.origin === "remote") { - usernameQuery.andWhere("user.host IS NOT NULL"); - } - - users = await usernameQuery - .orderBy("user.updatedAt", "DESC", "NULLS LAST") - .take(ps.limit) - .skip(ps.offset) - .getMany(); - } else { - const nameQuery = Users.createQueryBuilder("user") - .where( - new Brackets((qb) => { - qb.where("user.name ILIKE :query", { query: `%${ps.query}%` }); - - // Also search username if it qualifies as username - if (Users.validateLocalUsername(ps.query)) { - qb.orWhere("user.usernameLower LIKE :username", { - username: `%${ps.query.toLowerCase()}%`, - }); - } - }), - ) - .andWhere( - new Brackets((qb) => { - qb.where("user.updatedAt IS NULL").orWhere( - "user.updatedAt > :activeThreshold", - { activeThreshold: activeThreshold }, - ); - }), - ) - .andWhere("user.isSuspended = FALSE"); - - if (ps.origin === "local") { - nameQuery.andWhere("user.host IS NULL"); - } else if (ps.origin === "remote") { - nameQuery.andWhere("user.host IS NOT NULL"); - } - - users = await nameQuery - .orderBy("user.updatedAt", "DESC", "NULLS LAST") - .take(ps.limit) - .skip(ps.offset) - .getMany(); - - if (users.length < ps.limit) { - const profQuery = UserProfiles.createQueryBuilder("prof") - .select("prof.userId") - .where("prof.description ILIKE :query", { - query: `%${ps.query}%`, - }); - - if (ps.origin === "local") { - profQuery.andWhere("prof.userHost IS NULL"); - } else if (ps.origin === "remote") { - profQuery.andWhere("prof.userHost IS NOT NULL"); - } - - const query = Users.createQueryBuilder("user") - .where(`user.id IN (${profQuery.getQuery()})`) - .andWhere( - new Brackets((qb) => { - qb.where("user.updatedAt IS NULL").orWhere( - "user.updatedAt > :activeThreshold", - { activeThreshold: activeThreshold }, - ); - }), - ) - .andWhere("user.isSuspended = FALSE") - .setParameters(profQuery.getParameters()); - - users = users.concat( - await query - .orderBy("user.updatedAt", "DESC", "NULLS LAST") - .take(ps.limit) - .skip(ps.offset) - .getMany(), - ); - } - } - - return await Users.packMany(users, me, { detail: ps.detail }); -}); diff --git a/packages/backend/src/server/api/endpoints/users/show.ts b/packages/backend/src/server/api/endpoints/users/show.ts deleted file mode 100644 index 49cac81fdb..0000000000 --- a/packages/backend/src/server/api/endpoints/users/show.ts +++ /dev/null @@ -1,146 +0,0 @@ -import type { FindOptionsWhere } from "typeorm"; -import { In, IsNull } from "typeorm"; -import { resolveUser } from "@/remote/resolve-user.js"; -import { Users } from "@/models/index.js"; -import type { User } from "@/models/entities/user.js"; -import define from "../../define.js"; -import { apiLogger } from "../../logger.js"; -import { ApiError } from "../../error.js"; - -export const meta = { - tags: ["users"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - description: "Show the properties of a user.", - - res: { - optional: false, - nullable: false, - oneOf: [ - { - type: "object", - ref: "UserDetailed", - }, - { - type: "array", - items: { - type: "object", - ref: "UserDetailed", - }, - }, - ], - }, - - errors: { - failedToResolveRemoteUser: { - message: "Failed to resolve remote user.", - code: "FAILED_TO_RESOLVE_REMOTE_USER", - id: "ef7b9be4-9cba-4e6f-ab41-90ed171c7d3c", - kind: "server", - }, - - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "4362f8dc-731f-4ad8-a694-be5a88922a24", - }, - }, -} as const; - -export const paramDef = { - type: "object", - anyOf: [ - { - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], - }, - { - properties: { - userIds: { - type: "array", - uniqueItems: true, - items: { - type: "string", - format: "misskey:id", - }, - }, - }, - required: ["userIds"], - }, - { - properties: { - username: { type: "string" }, - host: { - type: "string", - nullable: true, - description: "The local host is represented with `null`.", - }, - }, - required: ["username"], - }, - ], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - let user; - - const isAdminOrModerator = me && (me.isAdmin || me.isModerator); - - if (ps.userIds) { - if (ps.userIds.length === 0) { - return []; - } - - const users = await Users.findBy( - isAdminOrModerator - ? { - id: In(ps.userIds), - } - : { - id: In(ps.userIds), - isSuspended: false, - }, - ); - - // リクエストされた通りに並べ替え - const _users: User[] = []; - for (const id of ps.userIds) { - _users.push(users.find((x) => x.id === id)!); - } - - return await Promise.all( - _users.map((u) => - Users.pack(u, me, { - detail: true, - }), - ), - ); - } else { - // Lookup user - if (typeof ps.host === "string" && typeof ps.username === "string") { - user = await resolveUser(ps.username, ps.host).catch((e) => { - apiLogger.warn(`failed to resolve remote user: ${e}`); - throw new ApiError(meta.errors.failedToResolveRemoteUser); - }); - } else { - const q: FindOptionsWhere<User> = - ps.userId != null - ? { id: ps.userId } - : { usernameLower: ps.username!.toLowerCase(), host: IsNull() }; - - user = await Users.findOneBy(q); - } - - if (user == null || (!isAdminOrModerator && user.isSuspended)) { - throw new ApiError(meta.errors.noSuchUser); - } - - return await Users.pack(user, me, { - detail: true, - }); - } -}); diff --git a/packages/backend/src/server/api/endpoints/users/stats.ts b/packages/backend/src/server/api/endpoints/users/stats.ts deleted file mode 100644 index 83e821f498..0000000000 --- a/packages/backend/src/server/api/endpoints/users/stats.ts +++ /dev/null @@ -1,225 +0,0 @@ -import { - DriveFiles, - Followings, - NoteFavorites, - NoteReactions, - Notes, - PageLikes, - PollVotes, - Users, -} from "@/models/index.js"; -import { awaitAll } from "@/prelude/await-all.js"; -import define from "../../define.js"; -import { ApiError } from "../../error.js"; - -export const meta = { - tags: ["users"], - - requireCredential: false, - requireCredentialPrivateMode: true, - - description: "Show statistics about a user.", - - errors: { - noSuchUser: { - message: "No such user.", - code: "NO_SUCH_USER", - id: "9e638e45-3b25-4ef7-8f95-07e8498f1819", - }, - }, - - res: { - type: "object", - optional: false, - nullable: false, - properties: { - notesCount: { - type: "integer", - optional: false, - nullable: false, - }, - repliesCount: { - type: "integer", - optional: false, - nullable: false, - }, - renotesCount: { - type: "integer", - optional: false, - nullable: false, - }, - repliedCount: { - type: "integer", - optional: false, - nullable: false, - }, - renotedCount: { - type: "integer", - optional: false, - nullable: false, - }, - pollVotesCount: { - type: "integer", - optional: false, - nullable: false, - }, - pollVotedCount: { - type: "integer", - optional: false, - nullable: false, - }, - localFollowingCount: { - type: "integer", - optional: false, - nullable: false, - }, - remoteFollowingCount: { - type: "integer", - optional: false, - nullable: false, - }, - localFollowersCount: { - type: "integer", - optional: false, - nullable: false, - }, - remoteFollowersCount: { - type: "integer", - optional: false, - nullable: false, - }, - followingCount: { - type: "integer", - optional: false, - nullable: false, - }, - followersCount: { - type: "integer", - optional: false, - nullable: false, - }, - sentReactionsCount: { - type: "integer", - optional: false, - nullable: false, - }, - receivedReactionsCount: { - type: "integer", - optional: false, - nullable: false, - }, - noteFavoritesCount: { - type: "integer", - optional: false, - nullable: false, - }, - pageLikesCount: { - type: "integer", - optional: false, - nullable: false, - }, - pageLikedCount: { - type: "integer", - optional: false, - nullable: false, - }, - driveFilesCount: { - type: "integer", - optional: false, - nullable: false, - }, - driveUsage: { - type: "integer", - optional: false, - nullable: false, - description: "Drive usage in bytes", - }, - }, - }, -} as const; - -export const paramDef = { - type: "object", - properties: { - userId: { type: "string", format: "misskey:id" }, - }, - required: ["userId"], -} as const; - -export default define(meta, paramDef, async (ps, me) => { - const user = await Users.findOneBy({ id: ps.userId }); - if (user == null) { - throw new ApiError(meta.errors.noSuchUser); - } - - const result = await awaitAll({ - notesCount: Notes.createQueryBuilder("note") - .where("note.userId = :userId", { userId: user.id }) - .getCount(), - repliesCount: Notes.createQueryBuilder("note") - .where("note.userId = :userId", { userId: user.id }) - .andWhere("note.replyId IS NOT NULL") - .getCount(), - renotesCount: Notes.createQueryBuilder("note") - .where("note.userId = :userId", { userId: user.id }) - .andWhere("note.renoteId IS NOT NULL") - .getCount(), - repliedCount: Notes.createQueryBuilder("note") - .where("note.replyUserId = :userId", { userId: user.id }) - .getCount(), - renotedCount: Notes.createQueryBuilder("note") - .where("note.renoteUserId = :userId", { userId: user.id }) - .getCount(), - pollVotesCount: PollVotes.createQueryBuilder("vote") - .where("vote.userId = :userId", { userId: user.id }) - .getCount(), - pollVotedCount: PollVotes.createQueryBuilder("vote") - .innerJoin("vote.note", "note") - .where("note.userId = :userId", { userId: user.id }) - .getCount(), - localFollowingCount: Followings.createQueryBuilder("following") - .where("following.followerId = :userId", { userId: user.id }) - .andWhere("following.followeeHost IS NULL") - .getCount(), - remoteFollowingCount: Followings.createQueryBuilder("following") - .where("following.followerId = :userId", { userId: user.id }) - .andWhere("following.followeeHost IS NOT NULL") - .getCount(), - localFollowersCount: Followings.createQueryBuilder("following") - .where("following.followeeId = :userId", { userId: user.id }) - .andWhere("following.followerHost IS NULL") - .getCount(), - remoteFollowersCount: Followings.createQueryBuilder("following") - .where("following.followeeId = :userId", { userId: user.id }) - .andWhere("following.followerHost IS NOT NULL") - .getCount(), - sentReactionsCount: NoteReactions.createQueryBuilder("reaction") - .where("reaction.userId = :userId", { userId: user.id }) - .getCount(), - receivedReactionsCount: NoteReactions.createQueryBuilder("reaction") - .innerJoin("reaction.note", "note") - .where("note.userId = :userId", { userId: user.id }) - .getCount(), - noteFavoritesCount: NoteFavorites.createQueryBuilder("favorite") - .where("favorite.userId = :userId", { userId: user.id }) - .getCount(), - pageLikesCount: PageLikes.createQueryBuilder("like") - .where("like.userId = :userId", { userId: user.id }) - .getCount(), - pageLikedCount: PageLikes.createQueryBuilder("like") - .innerJoin("like.page", "page") - .where("page.userId = :userId", { userId: user.id }) - .getCount(), - driveFilesCount: DriveFiles.createQueryBuilder("file") - .where("file.userId = :userId", { userId: user.id }) - .getCount(), - driveUsage: DriveFiles.calcDriveUsageOf(user), - }); - - result.followingCount = - result.localFollowingCount + result.remoteFollowingCount; - result.followersCount = - result.localFollowersCount + result.remoteFollowersCount; - - return result; -}); diff --git a/packages/backend/src/server/api/error.ts b/packages/backend/src/server/api/error.ts deleted file mode 100644 index c58561a04e..0000000000 --- a/packages/backend/src/server/api/error.ts +++ /dev/null @@ -1,36 +0,0 @@ -type E = { - message: string; - code: string; - id: string; - kind?: "client" | "server"; - httpStatusCode?: number; -}; - -export class ApiError extends Error { - public message: string; - public code: string; - public id: string; - public kind: string; - public httpStatusCode?: number; - public info?: any; - - constructor(e?: E | null | undefined, info?: any | null | undefined) { - if (e == null) - e = { - message: - "Internal error occurred. Please contact us if the error persists.", - code: "INTERNAL_ERROR", - id: "5d37dbcb-891e-41ca-a3d6-e690c97775ac", - kind: "server", - httpStatusCode: 500, - }; - - super(e.message); - this.message = e.message; - this.code = e.code; - this.id = e.id; - this.kind = e.kind || "client"; - this.httpStatusCode = e.httpStatusCode; - this.info = info; - } -} diff --git a/packages/backend/src/server/api/index.ts b/packages/backend/src/server/api/index.ts deleted file mode 100644 index b8e4231655..0000000000 --- a/packages/backend/src/server/api/index.ts +++ /dev/null @@ -1,230 +0,0 @@ -/** - * API Server - */ - -import Koa from "koa"; -import Router from "@koa/router"; -import multer from "@koa/multer"; -import bodyParser from "koa-bodyparser"; -import cors from "@koa/cors"; -import { - apiMastodonCompatible, - getClient, -} from "./mastodon/ApiMastodonCompatibleService.js"; -import { Instances, AccessTokens, Users } from "@/models/index.js"; -import config from "@/config/index.js"; -import fs from "fs"; -import endpoints from "./endpoints.js"; -import compatibility from "./compatibility.js"; -import handler from "./api-handler.js"; -import signup from "./private/signup.js"; -import signin from "./private/signin.js"; -import signupPending from "./private/signup-pending.js"; -import discord from "./service/discord.js"; -import github from "./service/github.js"; -import twitter from "./service/twitter.js"; -import { koaBody } from "koa-body"; -import { - convertId, - IdConvertType as IdType, -} from "../../../native-utils/built/index.js"; - -// re-export native rust id conversion (function and enum) -export { IdType, convertId }; - -// Init app -const app = new Koa(); - -app.use( - cors({ - origin: "*", - }), -); - -// No caching -app.use(async (ctx, next) => { - ctx.set("Cache-Control", "private, max-age=0, must-revalidate"); - await next(); -}); - -// Init router -const router = new Router(); -const mastoRouter = new Router(); -const mastoFileRouter = new Router(); -const errorRouter = new Router(); - -// Init multer instance -const upload = multer({ - storage: multer.diskStorage({}), - limits: { - fileSize: config.maxFileSize || 262144000, - files: 1, - }, -}); - -router.use( - bodyParser({ - // リクエストが multipart/form-data でない限りはJSONだと見なす - detectJSON: (ctx) => - !( - ctx.is("multipart/form-data") || - ctx.is("application/x-www-form-urlencoded") - ), - }), -); - -mastoRouter.use( - koaBody({ - multipart: true, - urlencoded: true, - }), -); - -mastoFileRouter.post("/v1/media", upload.single("file"), async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - let multipartData = await ctx.file; - if (!multipartData) { - ctx.body = { error: "No image" }; - ctx.status = 401; - return; - } - const data = await client.uploadMedia(multipartData); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } -}); -mastoFileRouter.post("/v2/media", upload.single("file"), async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - let multipartData = await ctx.file; - if (!multipartData) { - ctx.body = { error: "No image" }; - ctx.status = 401; - return; - } - const data = await client.uploadMedia(multipartData); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } -}); - -mastoRouter.use(async (ctx, next) => { - if (ctx.request.query) { - if (!ctx.request.body || Object.keys(ctx.request.body).length === 0) { - ctx.request.body = ctx.request.query; - } else { - ctx.request.body = { ...ctx.request.body, ...ctx.request.query }; - } - } - await next(); -}); - -apiMastodonCompatible(mastoRouter); - -/** - * Register endpoint handlers - */ -for (const endpoint of [...endpoints, ...compatibility]) { - if (endpoint.meta.requireFile) { - router.post( - `/${endpoint.name}`, - upload.single("file"), - handler.bind(null, endpoint), - ); - } else { - // 後方互換性のため - if (endpoint.name.includes("-")) { - router.post( - `/${endpoint.name.replace(/-/g, "_")}`, - handler.bind(null, endpoint), - ); - - if (endpoint.meta.allowGet) { - router.get( - `/${endpoint.name.replace(/-/g, "_")}`, - handler.bind(null, endpoint), - ); - } else { - router.get(`/${endpoint.name.replace(/-/g, "_")}`, async (ctx) => { - ctx.status = 405; - }); - } - } - - router.post(`/${endpoint.name}`, handler.bind(null, endpoint)); - - if (endpoint.meta.allowGet) { - router.get(`/${endpoint.name}`, handler.bind(null, endpoint)); - } else { - router.get(`/${endpoint.name}`, async (ctx) => { - ctx.status = 405; - }); - } - } -} - -router.post("/signup", signup); -router.post("/signin", signin); -router.post("/signup-pending", signupPending); - -router.use(discord.routes()); -router.use(github.routes()); -router.use(twitter.routes()); - -router.get("/v1/instance/peers", async (ctx) => { - const instances = await Instances.find({ - select: ["host"], - where: { - isSuspended: false, - }, - }); - - ctx.body = instances.map((instance) => instance.host); -}); - -router.post("/miauth/:session/check", async (ctx) => { - const token = await AccessTokens.findOneBy({ - session: ctx.params.session, - }); - - if (token?.session != null && !token.fetched) { - AccessTokens.update(token.id, { - fetched: true, - }); - - ctx.body = { - ok: true, - token: token.token, - user: await Users.pack(token.userId, null, { detail: true }), - }; - } else { - ctx.body = { - ok: false, - }; - } -}); - -// Return 404 for unknown API -errorRouter.all("(.*)", async (ctx) => { - ctx.status = 404; -}); - -// Register router -app.use(mastoFileRouter.routes()); -app.use(mastoRouter.routes()); -app.use(mastoRouter.allowedMethods()); -app.use(router.routes()); -app.use(errorRouter.routes()); - -export default app; diff --git a/packages/backend/src/server/api/limiter.ts b/packages/backend/src/server/api/limiter.ts deleted file mode 100644 index dd005ad136..0000000000 --- a/packages/backend/src/server/api/limiter.ts +++ /dev/null @@ -1,85 +0,0 @@ -import Limiter from "ratelimiter"; -import { CacheableLocalUser, User } from "@/models/entities/user.js"; -import Logger from "@/services/logger.js"; -import { redisClient } from "../../db/redis.js"; -import type { IEndpointMeta } from "./endpoints.js"; - -const logger = new Logger("limiter"); - -export const limiter = ( - limitation: IEndpointMeta["limit"] & { key: NonNullable<string> }, - actor: string, -) => - new Promise<void>((ok, reject) => { - if (process.env.NODE_ENV === "test") ok(); - - const hasShortTermLimit = typeof limitation.minInterval === "number"; - - const hasLongTermLimit = - typeof limitation.duration === "number" && - typeof limitation.max === "number"; - - if (hasShortTermLimit) { - min(); - } else if (hasLongTermLimit) { - max(); - } else { - ok(); - } - - // Short-term limit - function min(): void { - const minIntervalLimiter = new Limiter({ - id: `${actor}:${limitation.key}:min`, - duration: limitation.minInterval, - max: 1, - db: redisClient, - }); - - minIntervalLimiter.get((err, info) => { - if (err) { - return reject("ERR"); - } - - logger.debug( - `${actor} ${limitation.key} min remaining: ${info.remaining}`, - ); - - if (info.remaining === 0) { - reject("BRIEF_REQUEST_INTERVAL"); - } else { - if (hasLongTermLimit) { - max(); - } else { - ok(); - } - } - }); - } - - // Long term limit - function max(): void { - const limiter = new Limiter({ - id: `${actor}:${limitation.key}`, - duration: limitation.duration, - max: limitation.max, - db: redisClient, - }); - - limiter.get((err, info) => { - if (err) { - return reject("ERR"); - } - - logger.debug( - `${actor} ${limitation.key} max remaining: ${info.remaining}`, - ); - - if (info.remaining === 0) { - reject("RATE_LIMIT_EXCEEDED"); - } else { - ok(); - } - }); - } - }); diff --git a/packages/backend/src/server/api/logger.ts b/packages/backend/src/server/api/logger.ts deleted file mode 100644 index 083888ed77..0000000000 --- a/packages/backend/src/server/api/logger.ts +++ /dev/null @@ -1,3 +0,0 @@ -import Logger from "@/services/logger.js"; - -export const apiLogger = new Logger("api"); diff --git a/packages/backend/src/server/api/mastodon/ApiMastodonCompatibleService.ts b/packages/backend/src/server/api/mastodon/ApiMastodonCompatibleService.ts deleted file mode 100644 index e8dfe52812..0000000000 --- a/packages/backend/src/server/api/mastodon/ApiMastodonCompatibleService.ts +++ /dev/null @@ -1,140 +0,0 @@ -import Router from "@koa/router"; -import megalodon, { MegalodonInterface } from "@calckey/megalodon"; -import { apiAuthMastodon } from "./endpoints/auth.js"; -import { apiAccountMastodon } from "./endpoints/account.js"; -import { apiStatusMastodon } from "./endpoints/status.js"; -import { apiFilterMastodon } from "./endpoints/filter.js"; -import { apiTimelineMastodon } from "./endpoints/timeline.js"; -import { apiNotificationsMastodon } from "./endpoints/notifications.js"; -import { apiSearchMastodon } from "./endpoints/search.js"; -import { getInstance } from "./endpoints/meta.js"; - -export function getClient( - BASE_URL: string, - authorization: string | undefined, -): MegalodonInterface { - const accessTokenArr = authorization?.split(" ") ?? [null]; - const accessToken = accessTokenArr[accessTokenArr.length - 1]; - const generator = (megalodon as any).default; - const client = generator( - "misskey", - BASE_URL, - accessToken, - ) as MegalodonInterface; - return client; -} - -export function apiMastodonCompatible(router: Router): void { - apiAuthMastodon(router); - apiAccountMastodon(router); - apiStatusMastodon(router); - apiFilterMastodon(router); - apiTimelineMastodon(router); - apiNotificationsMastodon(router); - apiSearchMastodon(router); - - router.get("/v1/custom_emojis", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.request.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getInstanceCustomEmojis(); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - - router.get("/v1/instance", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.request.headers.authorization; - const client = getClient(BASE_URL, accessTokens); // we are using this here, because in private mode some info isnt - // displayed without being logged in - try { - const data = await client.getInstance(); - ctx.body = await getInstance(data.data); - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - - router.get("/v1/announcements", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.request.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getInstanceAnnouncements(); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - - router.post<{ Params: { id: string } }>( - "/v1/announcements/:id/dismiss", - async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.request.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.dismissInstanceAnnouncement(ctx.params.id); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - - router.get("/v1/filters", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.request.headers.authorization; - const client = getClient(BASE_URL, accessTokens); // we are using this here, because in private mode some info isnt - // displayed without being logged in - try { - const data = await client.getFilters(); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - - router.get("/v1/trends", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.request.headers.authorization; - const client = getClient(BASE_URL, accessTokens); // we are using this here, because in private mode some info isnt - // displayed without being logged in - try { - const data = await client.getInstanceTrends(); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - - router.get("/v1/preferences", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.request.headers.authorization; - const client = getClient(BASE_URL, accessTokens); // we are using this here, because in private mode some info isnt - // displayed without being logged in - try { - const data = await client.getPreferences(); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); -} diff --git a/packages/backend/src/server/api/mastodon/endpoints/account.ts b/packages/backend/src/server/api/mastodon/endpoints/account.ts deleted file mode 100644 index 70bdb74f34..0000000000 --- a/packages/backend/src/server/api/mastodon/endpoints/account.ts +++ /dev/null @@ -1,545 +0,0 @@ -import { Users } from "@/models/index.js"; -import { resolveUser } from "@/remote/resolve-user.js"; -import Router from "@koa/router"; -import { FindOptionsWhere, IsNull } from "typeorm"; -import { getClient } from "../ApiMastodonCompatibleService.js"; -import { argsToBools, limitToInt } from "./timeline.js"; -import { convertId, IdType } from "../../index.js"; - -const relationshipModel = { - id: "", - following: false, - followed_by: false, - delivery_following: false, - blocking: false, - blocked_by: false, - muting: false, - muting_notifications: false, - requested: false, - domain_blocking: false, - showing_reblogs: false, - endorsed: false, - notifying: false, - note: "", -}; - -export function apiAccountMastodon(router: Router): void { - router.get("/v1/accounts/verify_credentials", async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.verifyAccountCredentials(); - let acct = data.data; - acct.id = convertId(acct.id, IdType.MastodonId); - acct.display_name = acct.display_name || acct.username; - acct.url = `${BASE_URL}/@${acct.url}`; - acct.note = acct.note || ""; - acct.avatar_static = acct.avatar; - acct.header = acct.header || "https://http.cat/404"; - acct.header_static = acct.header || "https://http.cat/404"; - acct.source = { - note: acct.note, - fields: acct.fields, - privacy: "public", - sensitive: false, - language: "", - }; - console.log(acct); - ctx.body = acct; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.patch("/v1/accounts/update_credentials", async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.updateCredentials( - (ctx.request as any).body as any, - ); - let resp = data.data; - resp.id = convertId(resp.id, IdType.MastodonId); - ctx.body = resp; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.get("/v1/accounts/lookup", async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.search( - (ctx.request.query as any).acct, - "accounts", - ); - let resp = data.data.accounts[0]; - resp.id = convertId(resp.id, IdType.MastodonId); - ctx.body = resp; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.get<{ Params: { id: string } }>("/v1/accounts/:id", async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const calcId = convertId(ctx.params.id, IdType.CalckeyId); - const data = await client.getAccount(calcId); - let resp = data.data; - resp.id = convertId(resp.id, IdType.MastodonId); - ctx.body = resp; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.get<{ Params: { id: string } }>( - "/v1/accounts/:id/statuses", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getAccountStatuses( - convertId(ctx.params.id, IdType.CalckeyId), - argsToBools(limitToInt(ctx.query as any)), - ); - let resp = data.data; - for (let statIdx = 0; statIdx < resp.length; statIdx++) { - resp[statIdx].id = convertId(resp[statIdx].id, IdType.MastodonId); - resp[statIdx].in_reply_to_account_id = resp[statIdx] - .in_reply_to_account_id - ? convertId(resp[statIdx].in_reply_to_account_id, IdType.MastodonId) - : null; - resp[statIdx].in_reply_to_id = resp[statIdx].in_reply_to_id - ? convertId(resp[statIdx].in_reply_to_id, IdType.MastodonId) - : null; - let mentions = resp[statIdx].mentions; - for (let mtnIdx = 0; mtnIdx < mentions.length; mtnIdx++) { - resp[statIdx].mentions[mtnIdx].id = convertId( - mentions[mtnIdx].id, - IdType.MastodonId, - ); - } - } - ctx.body = resp; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.get<{ Params: { id: string } }>( - "/v1/accounts/:id/followers", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getAccountFollowers( - convertId(ctx.params.id, IdType.CalckeyId), - limitToInt(ctx.query as any), - ); - let resp = data.data; - for (let acctIdx = 0; acctIdx < resp.length; acctIdx++) { - resp[acctIdx].id = convertId(resp[acctIdx].id, IdType.MastodonId); - } - ctx.body = resp; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.get<{ Params: { id: string } }>( - "/v1/accounts/:id/following", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getAccountFollowing( - convertId(ctx.params.id, IdType.CalckeyId), - limitToInt(ctx.query as any), - ); - let resp = data.data; - for (let acctIdx = 0; acctIdx < resp.length; acctIdx++) { - resp[acctIdx].id = convertId(resp[acctIdx].id, IdType.MastodonId); - } - ctx.body = resp; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.get<{ Params: { id: string } }>( - "/v1/accounts/:id/lists", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getAccountLists(ctx.params.id); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.post<{ Params: { id: string } }>( - "/v1/accounts/:id/follow", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.followAccount( - convertId(ctx.params.id, IdType.CalckeyId), - ); - let acct = data.data; - acct.following = true; - acct.id = convertId(acct.id, IdType.MastodonId); - ctx.body = acct; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.post<{ Params: { id: string } }>( - "/v1/accounts/:id/unfollow", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.unfollowAccount( - convertId(ctx.params.id, IdType.CalckeyId), - ); - let acct = data.data; - acct.id = convertId(acct.id, IdType.MastodonId); - acct.following = false; - ctx.body = acct; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.post<{ Params: { id: string } }>( - "/v1/accounts/:id/block", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.blockAccount( - convertId(ctx.params.id, IdType.CalckeyId), - ); - let resp = data.data; - resp.id = convertId(resp.id, IdType.MastodonId); - ctx.body = resp; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.post<{ Params: { id: string } }>( - "/v1/accounts/:id/unblock", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.unblockAccount( - convertId(ctx.params.id, IdType.MastodonId), - ); - let resp = data.data; - resp.id = convertId(resp.id, IdType.MastodonId); - ctx.body = resp; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.post<{ Params: { id: string } }>( - "/v1/accounts/:id/mute", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.muteAccount( - convertId(ctx.params.id, IdType.CalckeyId), - (ctx.request as any).body as any, - ); - let resp = data.data; - resp.id = convertId(resp.id, IdType.MastodonId); - ctx.body = resp; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.post<{ Params: { id: string } }>( - "/v1/accounts/:id/unmute", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.unmuteAccount( - convertId(ctx.params.id, IdType.CalckeyId), - ); - let resp = data.data; - resp.id = convertId(resp.id, IdType.MastodonId); - ctx.body = resp; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.get("/v1/accounts/relationships", async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - let users; - try { - // TODO: this should be body - let ids = ctx.request.query ? ctx.request.query["id[]"] : null; - if (typeof ids === "string") { - ids = [ids]; - } - users = ids; - relationshipModel.id = ids?.toString() || "1"; - if (!ids) { - ctx.body = [relationshipModel]; - return; - } - - let reqIds = []; - for (let i = 0; i < ids.length; i++) { - reqIds.push(convertId(ids[i], IdType.CalckeyId)); - } - - const data = await client.getRelationships(reqIds); - let resp = data.data; - for (let acctIdx = 0; acctIdx < resp.length; acctIdx++) { - resp[acctIdx].id = convertId(resp[acctIdx].id, IdType.MastodonId); - } - ctx.body = resp; - } catch (e: any) { - console.error(e); - let data = e.response.data; - data.users = users; - console.error(data); - ctx.status = 401; - ctx.body = data; - } - }); - router.get("/v1/bookmarks", async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = (await client.getBookmarks( - limitToInt(ctx.query as any), - )) as any; - let resp = data.data; - for (let statIdx = 0; statIdx < resp.length; statIdx++) { - resp[statIdx].id = convertId(resp[statIdx].id, IdType.MastodonId); - resp[statIdx].in_reply_to_account_id = resp[statIdx] - .in_reply_to_account_id - ? convertId(resp[statIdx].in_reply_to_account_id, IdType.MastodonId) - : null; - resp[statIdx].in_reply_to_id = resp[statIdx].in_reply_to_id - ? convertId(resp[statIdx].in_reply_to_id, IdType.MastodonId) - : null; - let mentions = resp[statIdx].mentions; - for (let mtnIdx = 0; mtnIdx < mentions.length; mtnIdx++) { - resp[statIdx].mentions[mtnIdx].id = convertId( - mentions[mtnIdx].id, - IdType.MastodonId, - ); - } - } - ctx.body = resp; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.get("/v1/favourites", async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getFavourites(limitToInt(ctx.query as any)); - let resp = data.data; - for (let statIdx = 0; statIdx < resp.length; statIdx++) { - resp[statIdx].id = convertId(resp[statIdx].id, IdType.MastodonId); - resp[statIdx].in_reply_to_account_id = resp[statIdx] - .in_reply_to_account_id - ? convertId(resp[statIdx].in_reply_to_account_id, IdType.MastodonId) - : null; - resp[statIdx].in_reply_to_id = resp[statIdx].in_reply_to_id - ? convertId(resp[statIdx].in_reply_to_id, IdType.MastodonId) - : null; - let mentions = resp[statIdx].mentions; - for (let mtnIdx = 0; mtnIdx < mentions.length; mtnIdx++) { - resp[statIdx].mentions[mtnIdx].id = convertId( - mentions[mtnIdx].id, - IdType.MastodonId, - ); - } - } - ctx.body = resp; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.get("/v1/mutes", async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getMutes(limitToInt(ctx.query as any)); - let resp = data.data; - for (let acctIdx = 0; acctIdx < resp.length; acctIdx++) { - resp[acctIdx].id = convertId(resp[acctIdx].id, IdType.MastodonId); - } - ctx.body = resp; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.get("/v1/blocks", async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getBlocks(limitToInt(ctx.query as any)); - let resp = data.data; - for (let acctIdx = 0; acctIdx < resp.length; acctIdx++) { - resp[acctIdx].id = convertId(resp[acctIdx].id, IdType.MastodonId); - } - ctx.body = resp; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.get("/v1/follow_requests", async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getFollowRequests( - ((ctx.query as any) || { limit: 20 }).limit, - ); - let resp = data.data; - for (let acctIdx = 0; acctIdx < resp.length; acctIdx++) { - resp[acctIdx].id = convertId(resp[acctIdx].id, IdType.MastodonId); - } - ctx.body = resp; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.post<{ Params: { id: string } }>( - "/v1/follow_requests/:id/authorize", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.acceptFollowRequest( - convertId(ctx.params.id, IdType.CalckeyId), - ); - let resp = data.data; - resp.id = convertId(resp.id, IdType.MastodonId); - ctx.body = resp; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.post<{ Params: { id: string } }>( - "/v1/follow_requests/:id/reject", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.rejectFollowRequest( - convertId(ctx.params.id, IdType.CalckeyId), - ); - let resp = data.data; - resp.id = convertId(resp.id, IdType.MastodonId); - ctx.body = resp; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); -} diff --git a/packages/backend/src/server/api/mastodon/endpoints/auth.ts b/packages/backend/src/server/api/mastodon/endpoints/auth.ts deleted file mode 100644 index e2cfc47aff..0000000000 --- a/packages/backend/src/server/api/mastodon/endpoints/auth.ts +++ /dev/null @@ -1,81 +0,0 @@ -import megalodon, { MegalodonInterface } from "@calckey/megalodon"; -import Router from "@koa/router"; -import { koaBody } from "koa-body"; -import { getClient } from "../ApiMastodonCompatibleService.js"; -import bodyParser from "koa-bodyparser"; - -const readScope = [ - "read:account", - "read:drive", - "read:blocks", - "read:favorites", - "read:following", - "read:messaging", - "read:mutes", - "read:notifications", - "read:reactions", - "read:pages", - "read:page-likes", - "read:user-groups", - "read:channels", - "read:gallery", - "read:gallery-likes", -]; -const writeScope = [ - "write:account", - "write:drive", - "write:blocks", - "write:favorites", - "write:following", - "write:messaging", - "write:mutes", - "write:notes", - "write:notifications", - "write:reactions", - "write:votes", - "write:pages", - "write:page-likes", - "write:user-groups", - "write:channels", - "write:gallery", - "write:gallery-likes", -]; - -export function apiAuthMastodon(router: Router): void { - router.post("/v1/apps", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const client = getClient(BASE_URL, ""); - const body: any = ctx.request.body || ctx.request.query; - try { - let scope = body.scopes; - if (typeof scope === "string") scope = scope.split(" "); - const pushScope = new Set<string>(); - for (const s of scope) { - if (s.match(/^read/)) for (const r of readScope) pushScope.add(r); - if (s.match(/^write/)) for (const r of writeScope) pushScope.add(r); - } - const scopeArr = Array.from(pushScope); - - const red = body.redirect_uris; - const appData = await client.registerApp(body.client_name, { - scopes: scopeArr, - redirect_uris: red, - website: body.website, - }); - const returns = { - id: Math.floor(Math.random() * 100).toString(), - name: appData.name, - website: body.website, - redirect_uri: red, - client_id: Buffer.from(appData.url || "").toString("base64"), - client_secret: appData.clientSecret, - }; - console.log(returns); - ctx.body = returns; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); -} diff --git a/packages/backend/src/server/api/mastodon/endpoints/filter.ts b/packages/backend/src/server/api/mastodon/endpoints/filter.ts deleted file mode 100644 index d21bc1d330..0000000000 --- a/packages/backend/src/server/api/mastodon/endpoints/filter.ts +++ /dev/null @@ -1,84 +0,0 @@ -import megalodon, { MegalodonInterface } from "@calckey/megalodon"; -import Router from "@koa/router"; -import { getClient } from "../ApiMastodonCompatibleService.js"; - -export function apiFilterMastodon(router: Router): void { - router.get("/v1/filters", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.request.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - const body: any = ctx.request.body; - try { - const data = await client.getFilters(); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - - router.get("/v1/filters/:id", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.request.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - const body: any = ctx.request.body; - try { - const data = await client.getFilter(ctx.params.id); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - - router.post("/v1/filters", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.request.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - const body: any = ctx.request.body; - try { - const data = await client.createFilter(body.phrase, body.context, body); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - - router.post("/v1/filters/:id", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.request.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - const body: any = ctx.request.body; - try { - const data = await client.updateFilter( - ctx.params.id, - body.phrase, - body.context, - ); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - - router.delete("/v1/filters/:id", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.request.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - const body: any = ctx.request.body; - try { - const data = await client.deleteFilter(ctx.params.id); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); -} diff --git a/packages/backend/src/server/api/mastodon/endpoints/meta.ts b/packages/backend/src/server/api/mastodon/endpoints/meta.ts deleted file mode 100644 index d362d1b9e5..0000000000 --- a/packages/backend/src/server/api/mastodon/endpoints/meta.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { Entity } from "@calckey/megalodon"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { Users, Notes } from "@/models/index.js"; -import { IsNull, MoreThan } from "typeorm"; - -// TODO: add calckey features -export async function getInstance(response: Entity.Instance) { - const meta = await fetchMeta(true); - const totalUsers = Users.count({ where: { host: IsNull() } }); - const totalStatuses = Notes.count({ where: { userHost: IsNull() } }); - return { - uri: response.uri, - title: response.title || "Calckey", - short_description: - response.description.substring(0, 50) || "See real server website", - description: - response.description || - "This is a vanilla Calckey Instance. It doesnt seem to have a description. BTW you are using the Mastodon api to access this server :)", - email: response.email || "", - version: "3.0.0 compatible (3.5+ Calckey)", //I hope this version string is correct, we will need to test it. - urls: response.urls, - stats: { - user_count: await totalUsers, - status_count: await totalStatuses, - domain_count: response.stats.domain_count, - }, - thumbnail: response.thumbnail || "https://http.cat/404", - languages: meta.langs, - registrations: !meta.disableRegistration || response.registrations, - approval_required: !response.registrations, - invites_enabled: response.registrations, - configuration: { - accounts: { - max_featured_tags: 20, - }, - statuses: { - max_characters: 3000, - max_media_attachments: 4, - characters_reserved_per_url: response.uri.length, - }, - media_attachments: { - supported_mime_types: [ - "image/jpeg", - "image/png", - "image/gif", - "image/heic", - "image/heif", - "image/webp", - "image/avif", - "video/webm", - "video/mp4", - "video/quicktime", - "video/ogg", - "audio/wave", - "audio/wav", - "audio/x-wav", - "audio/x-pn-wave", - "audio/vnd.wave", - "audio/ogg", - "audio/vorbis", - "audio/mpeg", - "audio/mp3", - "audio/webm", - "audio/flac", - "audio/aac", - "audio/m4a", - "audio/x-m4a", - "audio/mp4", - "audio/3gpp", - "video/x-ms-asf", - ], - image_size_limit: 10485760, - image_matrix_limit: 16777216, - video_size_limit: 41943040, - video_frame_rate_limit: 60, - video_matrix_limit: 2304000, - }, - polls: { - max_options: 8, - max_characters_per_option: 50, - min_expiration: 300, - max_expiration: 2629746, - }, - }, - contact_account: { - id: "1", - username: "admin", - acct: "admin", - display_name: "admin", - locked: true, - bot: true, - discoverable: false, - group: false, - created_at: new Date().toISOString(), - note: "<p>Please refer to the original instance for the actual admin contact.</p>", - url: `${response.uri}/`, - avatar: `${response.uri}/static-assets/badges/info.png`, - avatar_static: `${response.uri}/static-assets/badges/info.png`, - header: "https://http.cat/404", - header_static: "https://http.cat/404", - followers_count: -1, - following_count: 0, - statuses_count: 0, - last_status_at: new Date().toISOString(), - noindex: true, - emojis: [], - fields: [], - }, - rules: [], - }; -} diff --git a/packages/backend/src/server/api/mastodon/endpoints/notifications.ts b/packages/backend/src/server/api/mastodon/endpoints/notifications.ts deleted file mode 100644 index 8508f1d486..0000000000 --- a/packages/backend/src/server/api/mastodon/endpoints/notifications.ts +++ /dev/null @@ -1,90 +0,0 @@ -import megalodon, { MegalodonInterface } from "@calckey/megalodon"; -import Router from "@koa/router"; -import { koaBody } from "koa-body"; -import { getClient } from "../ApiMastodonCompatibleService.js"; -import { toTextWithReaction } from "./timeline.js"; -function toLimitToInt(q: any) { - if (q.limit) if (typeof q.limit === "string") q.limit = parseInt(q.limit, 10); - return q; -} - -export function apiNotificationsMastodon(router: Router): void { - router.get("/v1/notifications", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.request.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - const body: any = ctx.request.body; - try { - const data = await client.getNotifications(toLimitToInt(ctx.query)); - const notfs = data.data; - const ret = notfs.map((n) => { - if (n.type !== "follow" && n.type !== "follow_request") { - if (n.type === "reaction") n.type = "favourite"; - n.status = toTextWithReaction( - n.status ? [n.status] : [], - ctx.hostname, - )[0]; - return n; - } else { - return n; - } - }); - ctx.body = ret; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - - router.get("/v1/notification/:id", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.request.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - const body: any = ctx.request.body; - try { - const dataRaw = await client.getNotification(ctx.params.id); - const data = dataRaw.data; - if (data.type !== "follow" && data.type !== "follow_request") { - if (data.type === "reaction") data.type = "favourite"; - ctx.body = toTextWithReaction([data as any], ctx.request.hostname)[0]; - } else { - ctx.body = data; - } - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - - router.post("/v1/notifications/clear", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.request.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - const body: any = ctx.request.body; - try { - const data = await client.dismissNotifications(); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - - router.post("/v1/notification/:id/dismiss", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.request.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - const body: any = ctx.request.body; - try { - const data = await client.dismissNotification(ctx.params.id); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); -} diff --git a/packages/backend/src/server/api/mastodon/endpoints/search.ts b/packages/backend/src/server/api/mastodon/endpoints/search.ts deleted file mode 100644 index e4990811ae..0000000000 --- a/packages/backend/src/server/api/mastodon/endpoints/search.ts +++ /dev/null @@ -1,135 +0,0 @@ -import megalodon, { MegalodonInterface } from "@calckey/megalodon"; -import Router from "@koa/router"; -import { getClient } from "../ApiMastodonCompatibleService.js"; -import axios from "axios"; -import { Converter } from "@calckey/megalodon"; -import { limitToInt } from "./timeline.js"; - -export function apiSearchMastodon(router: Router): void { - router.get("/v1/search", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.request.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - const body: any = ctx.request.body; - try { - const query: any = limitToInt(ctx.query); - const type = query.type || ""; - const data = await client.search(query.q, type, query); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.get("/v2/search", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const query: any = limitToInt(ctx.query); - const type = query.type; - if (type) { - const data = await client.search(query.q, type, query); - ctx.body = data.data; - } else { - const acct = await client.search(query.q, "accounts", query); - const stat = await client.search(query.q, "statuses", query); - const tags = await client.search(query.q, "hashtags", query); - ctx.body = { - accounts: acct.data.accounts, - statuses: stat.data.statuses, - hashtags: tags.data.hashtags, - }; - } - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.get("/v1/trends/statuses", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.headers.authorization; - try { - const data = await getHighlight( - BASE_URL, - ctx.request.hostname, - accessTokens, - ); - ctx.body = data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.get("/v2/suggestions", async (ctx) => { - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const accessTokens = ctx.headers.authorization; - try { - const query: any = ctx.query; - const data = await getFeaturedUser( - BASE_URL, - ctx.request.hostname, - accessTokens, - query.limit || 20, - ); - console.log(data); - ctx.body = data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); -} -async function getHighlight( - BASE_URL: string, - domain: string, - accessTokens: string | undefined, -) { - const accessTokenArr = accessTokens?.split(" ") ?? [null]; - const accessToken = accessTokenArr[accessTokenArr.length - 1]; - try { - const api = await axios.post(`${BASE_URL}/api/notes/featured`, { - i: accessToken, - }); - const data: MisskeyEntity.Note[] = api.data; - return data.map((note) => Converter.note(note, domain)); - } catch (e: any) { - console.log(e); - console.log(e.response.data); - return []; - } -} -async function getFeaturedUser( - BASE_URL: string, - host: string, - accessTokens: string | undefined, - limit: number, -) { - const accessTokenArr = accessTokens?.split(" ") ?? [null]; - const accessToken = accessTokenArr[accessTokenArr.length - 1]; - try { - const api = await axios.post(`${BASE_URL}/api/users`, { - i: accessToken, - limit, - origin: "local", - sort: "+follower", - state: "alive", - }); - const data: MisskeyEntity.UserDetail[] = api.data; - console.log(data); - return data.map((u) => { - return { - source: "past_interactions", - account: Converter.userDetail(u, host), - }; - }); - } catch (e: any) { - console.log(e); - console.log(e.response.data); - return []; - } -} diff --git a/packages/backend/src/server/api/mastodon/endpoints/status.ts b/packages/backend/src/server/api/mastodon/endpoints/status.ts deleted file mode 100644 index fcfbd6aaaf..0000000000 --- a/packages/backend/src/server/api/mastodon/endpoints/status.ts +++ /dev/null @@ -1,445 +0,0 @@ -import Router from "@koa/router"; -import { getClient } from "../ApiMastodonCompatibleService.js"; -import { emojiRegexAtStartToEnd } from "@/misc/emoji-regex.js"; -import axios from "axios"; -import querystring from "node:querystring"; -import qs from "qs"; -import { limitToInt } from "./timeline.js"; - -function normalizeQuery(data: any) { - const str = querystring.stringify(data); - return qs.parse(str); -} - -export function apiStatusMastodon(router: Router): void { - router.post("/v1/statuses", async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - let body: any = ctx.request.body; - if ( - (!body.poll && body["poll[options][]"]) || - (!body.media_ids && body["media_ids[]"]) - ) { - body = normalizeQuery(body); - } - const text = body.status; - const removed = text.replace(/@\S+/g, "").replace(/\s|/g, ""); - const isDefaultEmoji = emojiRegexAtStartToEnd.test(removed); - const isCustomEmoji = /^:[a-zA-Z0-9@_]+:$/.test(removed); - if ((body.in_reply_to_id && isDefaultEmoji) || isCustomEmoji) { - const a = await client.createEmojiReaction( - body.in_reply_to_id, - removed, - ); - ctx.body = a.data; - } - if (body.in_reply_to_id && removed === "/unreact") { - try { - const id = body.in_reply_to_id; - const post = await client.getStatus(id); - const react = post.data.emoji_reactions.filter((e) => e.me)[0].name; - const data = await client.deleteEmojiReaction(id, react); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - } - if (!body.media_ids) body.media_ids = undefined; - if (body.media_ids && !body.media_ids.length) body.media_ids = undefined; - const { sensitive } = body; - body.sensitive = - typeof sensitive === "string" ? sensitive === "true" : sensitive; - const data = await client.postStatus(text, body); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.get<{ Params: { id: string } }>("/v1/statuses/:id", async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getStatus(ctx.params.id); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.delete<{ Params: { id: string } }>("/v1/statuses/:id", async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.deleteStatus(ctx.params.id); - ctx.body = data.data; - } catch (e: any) { - console.error(e.response.data, request.params.id); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - interface IReaction { - id: string; - createdAt: string; - user: MisskeyEntity.User; - type: string; - } - router.get<{ Params: { id: string } }>( - "/v1/statuses/:id/context", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const id = ctx.params.id; - const data = await client.getStatusContext( - id, - limitToInt(ctx.query as any), - ); - const status = await client.getStatus(id); - let reqInstance = axios.create({ - headers: { - Authorization: ctx.headers.authorization, - }, - }); - const reactionsAxios = await reqInstance.get( - `${BASE_URL}/api/notes/reactions?noteId=${id}`, - ); - const reactions: IReaction[] = reactionsAxios.data; - const text = reactions - .map((r) => `${r.type.replace("@.", "")} ${r.user.username}`) - .join("<br />"); - data.data.descendants.unshift( - statusModel( - status.data.id, - status.data.account.id, - status.data.emojis, - text, - ), - ); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.get<{ Params: { id: string } }>( - "/v1/statuses/:id/reblogged_by", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getStatusRebloggedBy(ctx.params.id); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.get<{ Params: { id: string } }>( - "/v1/statuses/:id/favourited_by", - async (ctx) => { - ctx.body = []; - }, - ); - router.post<{ Params: { id: string } }>( - "/v1/statuses/:id/favourite", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - const react = await getFirstReaction(BASE_URL, accessTokens); - try { - const a = (await client.createEmojiReaction( - ctx.params.id, - react, - )) as any; - //const data = await client.favouriteStatus(ctx.params.id) as any; - ctx.body = a.data; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.post<{ Params: { id: string } }>( - "/v1/statuses/:id/unfavourite", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - const react = await getFirstReaction(BASE_URL, accessTokens); - try { - const data = await client.deleteEmojiReaction(ctx.params.id, react); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - - router.post<{ Params: { id: string } }>( - "/v1/statuses/:id/reblog", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.reblogStatus(ctx.params.id); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - - router.post<{ Params: { id: string } }>( - "/v1/statuses/:id/unreblog", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.unreblogStatus(ctx.params.id); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - - router.post<{ Params: { id: string } }>( - "/v1/statuses/:id/bookmark", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.bookmarkStatus(ctx.params.id); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - - router.post<{ Params: { id: string } }>( - "/v1/statuses/:id/unbookmark", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = (await client.unbookmarkStatus(ctx.params.id)) as any; - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - - router.post<{ Params: { id: string } }>( - "/v1/statuses/:id/pin", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.pinStatus(ctx.params.id); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - - router.post<{ Params: { id: string } }>( - "/v1/statuses/:id/unpin", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.unpinStatus(ctx.params.id); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.get<{ Params: { id: string } }>("/v1/media/:id", async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getMedia(ctx.params.id); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.put<{ Params: { id: string } }>("/v1/media/:id", async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.updateMedia( - ctx.params.id, - ctx.request.body as any, - ); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.get<{ Params: { id: string } }>("/v1/polls/:id", async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getPoll(ctx.params.id); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.post<{ Params: { id: string } }>( - "/v1/polls/:id/votes", - async (ctx) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.votePoll( - ctx.params.id, - (ctx.request.body as any).choices, - ); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); -} - -async function getFirstReaction( - BASE_URL: string, - accessTokens: string | undefined, -) { - const accessTokenArr = accessTokens?.split(" ") ?? [null]; - const accessToken = accessTokenArr[accessTokenArr.length - 1]; - let react = "⭐"; - try { - const api = await axios.post(`${BASE_URL}/api/i/registry/get-unsecure`, { - scope: ["client", "base"], - key: "reactions", - i: accessToken, - }); - const reactRaw = api.data; - react = Array.isArray(reactRaw) ? api.data[0] : "⭐"; - console.log(api.data); - return react; - } catch (e) { - return react; - } -} - -export function statusModel( - id: string | null, - acctId: string | null, - emojis: MastodonEntity.Emoji[], - content: string, -) { - const now = Math.floor(new Date().getTime() / 1000); - return { - id: "9atm5frjhb", - uri: "https://http.cat/404", // "" - url: "https://http.cat/404", // "", - account: { - id: "9arzuvv0sw", - username: "Reactions", - acct: "Reactions", - display_name: "Reactions to this post", - locked: false, - created_at: now, - followers_count: 0, - following_count: 0, - statuses_count: 0, - note: "", - url: "https://http.cat/404", - avatar: "/static-assets/badges/info.png", - avatar_static: "/static-assets/badges/info.png", - header: "https://http.cat/404", // "" - header_static: "https://http.cat/404", // "" - emojis: [], - fields: [], - moved: null, - bot: false, - }, - in_reply_to_id: id, - in_reply_to_account_id: acctId, - reblog: null, - content: `<p>${content}</p>`, - plain_content: null, - created_at: now, - emojis: emojis, - replies_count: 0, - reblogs_count: 0, - favourites_count: 0, - favourited: false, - reblogged: false, - muted: false, - sensitive: false, - spoiler_text: "", - visibility: "public" as const, - media_attachments: [], - mentions: [], - tags: [], - card: null, - poll: null, - application: null, - language: null, - pinned: false, - emoji_reactions: [], - bookmarked: false, - quote: null, - }; -} diff --git a/packages/backend/src/server/api/mastodon/endpoints/timeline.ts b/packages/backend/src/server/api/mastodon/endpoints/timeline.ts deleted file mode 100644 index ce3a4dc958..0000000000 --- a/packages/backend/src/server/api/mastodon/endpoints/timeline.ts +++ /dev/null @@ -1,336 +0,0 @@ -import Router from "@koa/router"; -import megalodon, { Entity, MegalodonInterface } from "@calckey/megalodon"; -import { getClient } from "../ApiMastodonCompatibleService.js"; -import { statusModel } from "./status.js"; -import Autolinker from "autolinker"; -import { ParsedUrlQuery } from "querystring"; - -export function limitToInt(q: ParsedUrlQuery) { - let object: any = q; - if (q.limit) - if (typeof q.limit === "string") object.limit = parseInt(q.limit, 10); - if (q.offset) - if (typeof q.offset === "string") object.offset = parseInt(q.offset, 10); - return object; -} - -export function argsToBools(q: ParsedUrlQuery) { - // Values taken from https://docs.joinmastodon.org/client/intro/#boolean - const toBoolean = (value: string) => - !["0", "f", "F", "false", "FALSE", "off", "OFF"].includes(value); - - let object: any = q; - if (q.only_media) - if (typeof q.only_media === "string") - object.only_media = toBoolean(q.only_media); - if (q.exclude_replies) - if (typeof q.exclude_replies === "string") - object.exclude_replies = toBoolean(q.exclude_replies); - return q; -} - -export function toTextWithReaction(status: Entity.Status[], host: string) { - return status.map((t) => { - if (!t) return statusModel(null, null, [], "no content"); - t.quote = null as any; - if (!t.emoji_reactions) return t; - if (t.reblog) t.reblog = toTextWithReaction([t.reblog], host)[0]; - const reactions = t.emoji_reactions.map((r) => { - const emojiNotation = r.url ? `:${r.name.replace("@.", "")}:` : r.name; - return `${emojiNotation} (${r.count}${r.me ? `* ` : ""})`; - }); - const reaction = t.emoji_reactions as Entity.Reaction[]; - const emoji = t.emojis || []; - for (const r of reaction) { - if (!r.url) continue; - emoji.push({ - shortcode: r.name, - url: r.url, - static_url: r.url, - visible_in_picker: true, - category: "", - }); - } - const isMe = reaction.findIndex((r) => r.me) > -1; - const total = reaction.reduce((sum, reaction) => sum + reaction.count, 0); - t.favourited = isMe; - t.favourites_count = total; - t.emojis = emoji; - t.content = `<p>${autoLinker(t.content, host)}</p><p>${reactions.join( - ", ", - )}</p>`; - return t; - }); -} -export function autoLinker(input: string, host: string) { - return Autolinker.link(input, { - hashtag: "twitter", - mention: "twitter", - email: false, - stripPrefix: false, - replaceFn: function (match) { - switch (match.type) { - case "url": - return true; - case "mention": - console.log("Mention: ", match.getMention()); - console.log("Mention Service Name: ", match.getServiceName()); - return `<a href="https://${host}/@${encodeURIComponent( - match.getMention(), - )}" target="_blank">@${match.getMention()}</a>`; - case "hashtag": - console.log("Hashtag: ", match.getHashtag()); - return `<a href="https://${host}/tags/${encodeURIComponent( - match.getHashtag(), - )}" target="_blank">#${match.getHashtag()}</a>`; - } - return false; - }, - }); -} - -export function apiTimelineMastodon(router: Router): void { - router.get("/v1/timelines/public", async (ctx, reply) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const query: any = ctx.query; - const data = query.local - ? await client.getLocalTimeline(argsToBools(limitToInt(query))) - : await client.getPublicTimeline(argsToBools(limitToInt(query))); - ctx.body = toTextWithReaction(data.data, ctx.hostname); - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.get<{ Params: { hashtag: string } }>( - "/v1/timelines/tag/:hashtag", - async (ctx, reply) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getTagTimeline( - ctx.params.hashtag, - argsToBools(limitToInt(ctx.query)), - ); - ctx.body = toTextWithReaction(data.data, ctx.hostname); - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.get("/v1/timelines/home", async (ctx, reply) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getHomeTimeline(limitToInt(ctx.query)); - ctx.body = toTextWithReaction(data.data, ctx.hostname); - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.get<{ Params: { listId: string } }>( - "/v1/timelines/list/:listId", - async (ctx, reply) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getListTimeline( - ctx.params.listId, - limitToInt(ctx.query), - ); - ctx.body = toTextWithReaction(data.data, ctx.hostname); - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.get("/v1/conversations", async (ctx, reply) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getConversationTimeline(limitToInt(ctx.query)); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.get("/v1/lists", async (ctx, reply) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getLists(); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.get<{ Params: { id: string } }>( - "/v1/lists/:id", - async (ctx, reply) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getList(ctx.params.id); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.post("/v1/lists", async (ctx, reply) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.createList((ctx.query as any).title); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }); - router.put<{ Params: { id: string } }>( - "/v1/lists/:id", - async (ctx, reply) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.updateList(ctx.params.id, ctx.query as any); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.delete<{ Params: { id: string } }>( - "/v1/lists/:id", - async (ctx, reply) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.deleteList(ctx.params.id); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.get<{ Params: { id: string } }>( - "/v1/lists/:id/accounts", - async (ctx, reply) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.getAccountsInList( - ctx.params.id, - ctx.query as any, - ); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.post<{ Params: { id: string } }>( - "/v1/lists/:id/accounts", - async (ctx, reply) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.addAccountsToList( - ctx.params.id, - (ctx.query as any).account_ids, - ); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); - router.delete<{ Params: { id: string } }>( - "/v1/lists/:id/accounts", - async (ctx, reply) => { - const BASE_URL = `${ctx.protocol}://${ctx.hostname}`; - const accessTokens = ctx.headers.authorization; - const client = getClient(BASE_URL, accessTokens); - try { - const data = await client.deleteAccountsFromList( - ctx.params.id, - (ctx.query as any).account_ids, - ); - ctx.body = data.data; - } catch (e: any) { - console.error(e); - console.error(e.response.data); - ctx.status = 401; - ctx.body = e.response.data; - } - }, - ); -} -function escapeHTML(str: string) { - if (!str) { - return ""; - } - return str - .replace(/&/g, "&") - .replace(/</g, "<") - .replace(/>/g, ">") - .replace(/"/g, """) - .replace(/'/g, "'"); -} -function nl2br(str: string) { - if (!str) { - return ""; - } - str = str.replace(/\r\n/g, "<br />"); - str = str.replace(/(\n|\r)/g, "<br />"); - return str; -} diff --git a/packages/backend/src/server/api/openapi/errors.ts b/packages/backend/src/server/api/openapi/errors.ts deleted file mode 100644 index 0fe229d88e..0000000000 --- a/packages/backend/src/server/api/openapi/errors.ts +++ /dev/null @@ -1,71 +0,0 @@ -export const errors = { - "400": { - INVALID_PARAM: { - value: { - error: { - message: "Invalid param.", - code: "INVALID_PARAM", - id: "3d81ceae-475f-4600-b2a8-2bc116157532", - }, - }, - }, - }, - "401": { - CREDENTIAL_REQUIRED: { - value: { - error: { - message: "Credential required.", - code: "CREDENTIAL_REQUIRED", - id: "1384574d-a912-4b81-8601-c7b1c4085df1", - }, - }, - }, - }, - "403": { - AUTHENTICATION_FAILED: { - value: { - error: { - message: - "Authentication failed. Please ensure your token is correct.", - code: "AUTHENTICATION_FAILED", - id: "b0a7f5f8-dc2f-4171-b91f-de88ad238e14", - }, - }, - }, - }, - "418": { - I_AM_CALC: { - value: { - error: { - message: - "You sent a request to Calc, Calckey's resident stoner furry, instead of the server.", - code: "I_AM_CALC", - id: "60c46cd1-f23a-46b1-bebe-5d2b73951a84", - }, - }, - }, - }, - "429": { - RATE_LIMIT_EXCEEDED: { - value: { - error: { - message: "Rate limit exceeded. Please try again later.", - code: "RATE_LIMIT_EXCEEDED", - id: "d5826d14-3982-4d2e-8011-b9e9f02499ef", - }, - }, - }, - }, - "500": { - INTERNAL_ERROR: { - value: { - error: { - message: - "Internal error occurred. Please contact us if the error persists.", - code: "INTERNAL_ERROR", - id: "5d37dbcb-891e-41ca-a3d6-e690c97775ac", - }, - }, - }, - }, -}; diff --git a/packages/backend/src/server/api/openapi/gen-spec.ts b/packages/backend/src/server/api/openapi/gen-spec.ts deleted file mode 100644 index dfaacf9e50..0000000000 --- a/packages/backend/src/server/api/openapi/gen-spec.ts +++ /dev/null @@ -1,226 +0,0 @@ -import endpoints from "../endpoints.js"; -import config from "@/config/index.js"; -import { errors as basicErrors } from "./errors.js"; -import { schemas, convertSchemaToOpenApiSchema } from "./schemas.js"; - -export function genOpenapiSpec() { - const spec = { - openapi: "3.0.0", - - info: { - version: "v1", - title: "Calckey API", - "x-logo": { url: "/static-assets/api-doc.png" }, - }, - - externalDocs: { - description: "Repository", - url: "https://codeberg.org/calckey/calckey", - }, - - servers: [ - { - url: config.apiUrl, - }, - ], - - paths: {} as any, - - components: { - schemas: schemas, - - securitySchemes: { - ApiKeyAuth: { - type: "apiKey", - in: "body", - name: "i", - }, - // TODO: change this to oauth2 when the remaining oauth stuff is set up - Bearer: { - type: "http", - scheme: "bearer", - }, - }, - }, - }; - - for (const endpoint of endpoints.filter((ep) => !ep.meta.secure)) { - const errors = {} as any; - - if (endpoint.meta.errors) { - for (const e of Object.values(endpoint.meta.errors)) { - errors[e.code] = { - value: { - error: e, - }, - }; - } - } - - const resSchema = endpoint.meta.res - ? convertSchemaToOpenApiSchema(endpoint.meta.res) - : {}; - - let desc = - (endpoint.meta.description - ? endpoint.meta.description - : "No description provided.") + "\n\n"; - desc += `**Credential required**: *${ - endpoint.meta.requireCredential ? "Yes" : "No" - }*`; - if (endpoint.meta.kind) { - const kind = endpoint.meta.kind; - desc += ` / **Permission**: *${kind}*`; - } - - const requestType = endpoint.meta.requireFile - ? "multipart/form-data" - : "application/json"; - const schema = endpoint.params; - - if (endpoint.meta.requireFile) { - schema.properties.file = { - type: "string", - format: "binary", - description: "The file contents.", - }; - schema.required.push("file"); - } - - const security = [ - { - ApiKeyAuth: [], - }, - { - Bearer: [], - }, - ]; - if (!endpoint.meta.requireCredential) { - // add this to make authentication optional - security.push({}); - } - - const info = { - operationId: endpoint.name, - summary: endpoint.name, - description: desc, - externalDocs: { - description: "Source code", - url: `https://codeberg.org/calckey/calckey/src/branch/develop/packages/backend/src/server/api/endpoints/${endpoint.name}.ts`, - }, - tags: endpoint.meta.tags || undefined, - security, - requestBody: { - required: true, - content: { - [requestType]: { - schema, - }, - }, - }, - responses: { - ...(endpoint.meta.res - ? { - "200": { - description: "OK (with results)", - content: { - "application/json": { - schema: resSchema, - }, - }, - }, - } - : { - "204": { - description: "OK (without any results)", - }, - }), - "400": { - description: "Client error", - content: { - "application/json": { - schema: { - $ref: "#/components/schemas/Error", - }, - examples: { ...errors, ...basicErrors["400"] }, - }, - }, - }, - "401": { - description: "Authentication error", - content: { - "application/json": { - schema: { - $ref: "#/components/schemas/Error", - }, - examples: basicErrors["401"], - }, - }, - }, - "403": { - description: "Forbidden error", - content: { - "application/json": { - schema: { - $ref: "#/components/schemas/Error", - }, - examples: basicErrors["403"], - }, - }, - }, - "418": { - description: "I'm Calc", - content: { - "application/json": { - schema: { - $ref: "#/components/schemas/Error", - }, - examples: basicErrors["418"], - }, - }, - }, - ...(endpoint.meta.limit - ? { - "429": { - description: "To many requests", - content: { - "application/json": { - schema: { - $ref: "#/components/schemas/Error", - }, - examples: basicErrors["429"], - }, - }, - }, - } - : {}), - "500": { - description: "Internal server error", - content: { - "application/json": { - schema: { - $ref: "#/components/schemas/Error", - }, - examples: basicErrors["500"], - }, - }, - }, - }, - }; - - const path = { - post: info, - }; - if (endpoint.meta.allowGet) { - path.get = { ...info }; - // API Key authentication is not permitted for GET requests - path.get.security = path.get.security.filter( - (elem) => !Object.prototype.hasOwnProperty.call(elem, "ApiKeyAuth"), - ); - } - - spec.paths[`/${endpoint.name}`] = path; - } - - return spec; -} diff --git a/packages/backend/src/server/api/openapi/schemas.ts b/packages/backend/src/server/api/openapi/schemas.ts deleted file mode 100644 index 68b15d5677..0000000000 --- a/packages/backend/src/server/api/openapi/schemas.ts +++ /dev/null @@ -1,66 +0,0 @@ -import type { Schema } from "@/misc/schema.js"; -import { refs } from "@/misc/schema.js"; - -export function convertSchemaToOpenApiSchema(schema: Schema) { - const res: any = schema; - - if (schema.type === "object" && schema.properties) { - res.required = Object.entries(schema.properties) - .filter(([k, v]) => !v.optional) - .map(([k]) => k); - - for (const k of Object.keys(schema.properties)) { - res.properties[k] = convertSchemaToOpenApiSchema(schema.properties[k]); - } - } - - if (schema.type === "array" && schema.items) { - res.items = convertSchemaToOpenApiSchema(schema.items); - } - - if (schema.anyOf) res.anyOf = schema.anyOf.map(convertSchemaToOpenApiSchema); - if (schema.oneOf) res.oneOf = schema.oneOf.map(convertSchemaToOpenApiSchema); - if (schema.allOf) res.allOf = schema.allOf.map(convertSchemaToOpenApiSchema); - - if (schema.ref) { - res.$ref = `#/components/schemas/${schema.ref}`; - } - - return res; -} - -export const schemas = { - Error: { - type: "object", - properties: { - error: { - type: "object", - description: "An error object.", - properties: { - code: { - type: "string", - description: "An error code. Unique within the endpoint.", - }, - message: { - type: "string", - description: "An error message.", - }, - id: { - type: "string", - format: "uuid", - description: "An error ID. This ID is static.", - }, - }, - required: ["code", "id", "message"], - }, - }, - required: ["error"], - }, - - ...Object.fromEntries( - Object.entries(refs).map(([key, schema]) => [ - key, - convertSchemaToOpenApiSchema(schema), - ]), - ), -}; diff --git a/packages/backend/src/server/api/private/signin.ts b/packages/backend/src/server/api/private/signin.ts deleted file mode 100644 index ef5b137813..0000000000 --- a/packages/backend/src/server/api/private/signin.ts +++ /dev/null @@ -1,270 +0,0 @@ -import type Koa from "koa"; -import * as speakeasy from "speakeasy"; -import signin from "../common/signin.js"; -import config from "@/config/index.js"; -import { - Users, - Signins, - UserProfiles, - UserSecurityKeys, - AttestationChallenges, -} from "@/models/index.js"; -import type { ILocalUser } from "@/models/entities/user.js"; -import { genId } from "@/misc/gen-id.js"; -import { - comparePassword, - hashPassword, - isOldAlgorithm, -} from "@/misc/password.js"; -import { verifyLogin, hash } from "../2fa.js"; -import { randomBytes } from "node:crypto"; -import { IsNull } from "typeorm"; -import { limiter } from "../limiter.js"; -import { getIpHash } from "@/misc/get-ip-hash.js"; - -export default async (ctx: Koa.Context) => { - ctx.set("Access-Control-Allow-Origin", config.url); - ctx.set("Access-Control-Allow-Credentials", "true"); - - const body = ctx.request.body as any; - const username = body["username"]; - const password = body["password"]; - const token = body["token"]; - - function error(status: number, error: { id: string }) { - ctx.status = status; - ctx.body = { error }; - } - - try { - // not more than 1 attempt per second and not more than 10 attempts per hour - await limiter( - { key: "signin", duration: 60 * 60 * 1000, max: 10, minInterval: 1000 }, - getIpHash(ctx.ip), - ); - } catch (err) { - ctx.status = 429; - ctx.body = { - error: { - message: "Too many failed attempts to sign in. Try again later.", - code: "TOO_MANY_AUTHENTICATION_FAILURES", - id: "22d05606-fbcf-421a-a2db-b32610dcfd1b", - }, - }; - return; - } - - if (typeof username !== "string") { - ctx.status = 400; - return; - } - - if (typeof password !== "string") { - ctx.status = 400; - return; - } - - if (token != null && typeof token !== "string") { - ctx.status = 400; - return; - } - - // Fetch user - const user = (await Users.findOneBy({ - usernameLower: username.toLowerCase(), - host: IsNull(), - })) as ILocalUser; - - if (user == null) { - error(404, { - id: "6cc579cc-885d-43d8-95c2-b8c7fc963280", - }); - return; - } - - if (user.isSuspended) { - error(403, { - id: "e03a5f46-d309-4865-9b69-56282d94e1eb", - }); - return; - } - - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - // Compare password - const same = await comparePassword(password, profile.password!); - - if (same && isOldAlgorithm(profile.password!)) { - profile.password = await hashPassword(password); - await UserProfiles.save(profile); - } - - async function fail(status?: number, failure?: { id: string }) { - // Append signin history - await Signins.insert({ - id: genId(), - createdAt: new Date(), - userId: user.id, - ip: ctx.ip, - headers: ctx.headers, - success: false, - }); - - error( - status || 500, - failure || { id: "4e30e80c-e338-45a0-8c8f-44455efa3b76" }, - ); - } - - if (!profile.twoFactorEnabled) { - if (same) { - signin(ctx, user); - return; - } else { - await fail(403, { - id: "932c904e-9460-45b7-9ce6-7ed33be7eb2c", - }); - return; - } - } - - if (token) { - if (!same) { - await fail(403, { - id: "932c904e-9460-45b7-9ce6-7ed33be7eb2c", - }); - return; - } - - const verified = (speakeasy as any).totp.verify({ - secret: profile.twoFactorSecret, - encoding: "base32", - token: token, - window: 2, - }); - - if (verified) { - signin(ctx, user); - return; - } else { - await fail(403, { - id: "cdf1235b-ac71-46d4-a3a6-84ccce48df6f", - }); - return; - } - } else if (body.credentialId) { - if (!(same || profile.usePasswordLessLogin)) { - await fail(403, { - id: "932c904e-9460-45b7-9ce6-7ed33be7eb2c", - }); - return; - } - - const clientDataJSON = Buffer.from(body.clientDataJSON, "hex"); - const clientData = JSON.parse(clientDataJSON.toString("utf-8")); - const challenge = await AttestationChallenges.findOneBy({ - userId: user.id, - id: body.challengeId, - registrationChallenge: false, - challenge: hash(clientData.challenge).toString("hex"), - }); - - if (!challenge) { - await fail(403, { - id: "2715a88a-2125-4013-932f-aa6fe72792da", - }); - return; - } - - await AttestationChallenges.delete({ - userId: user.id, - id: body.challengeId, - }); - - if (new Date().getTime() - challenge.createdAt.getTime() >= 5 * 60 * 1000) { - await fail(403, { - id: "2715a88a-2125-4013-932f-aa6fe72792da", - }); - return; - } - - const securityKey = await UserSecurityKeys.findOneBy({ - id: Buffer.from( - body.credentialId.replace(/-/g, "+").replace(/_/g, "/"), - "base64", - ).toString("hex"), - }); - - if (!securityKey) { - await fail(403, { - id: "66269679-aeaf-4474-862b-eb761197e046", - }); - return; - } - - const isValid = verifyLogin({ - publicKey: Buffer.from(securityKey.publicKey, "hex"), - authenticatorData: Buffer.from(body.authenticatorData, "hex"), - clientDataJSON, - clientData, - signature: Buffer.from(body.signature, "hex"), - challenge: challenge.challenge, - }); - - if (isValid) { - signin(ctx, user); - return; - } else { - await fail(403, { - id: "93b86c4b-72f9-40eb-9815-798928603d1e", - }); - return; - } - } else { - if (!(same || profile.usePasswordLessLogin)) { - await fail(403, { - id: "932c904e-9460-45b7-9ce6-7ed33be7eb2c", - }); - return; - } - - const keys = await UserSecurityKeys.findBy({ - userId: user.id, - }); - - if (keys.length === 0) { - await fail(403, { - id: "f27fd449-9af4-4841-9249-1f989b9fa4a4", - }); - return; - } - - // 32 byte challenge - const challenge = randomBytes(32) - .toString("base64") - .replace(/=/g, "") - .replace(/\+/g, "-") - .replace(/\//g, "_"); - - const challengeId = genId(); - - await AttestationChallenges.insert({ - userId: user.id, - id: challengeId, - challenge: hash(Buffer.from(challenge, "utf-8")).toString("hex"), - createdAt: new Date(), - registrationChallenge: false, - }); - - ctx.body = { - challenge, - challengeId, - securityKeys: keys.map((key) => ({ - id: key.id, - })), - }; - ctx.status = 200; - return; - } - // never get here -}; diff --git a/packages/backend/src/server/api/private/signup-pending.ts b/packages/backend/src/server/api/private/signup-pending.ts deleted file mode 100644 index c7fdcea221..0000000000 --- a/packages/backend/src/server/api/private/signup-pending.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type Koa from "koa"; -import { Users, UserPendings, UserProfiles } from "@/models/index.js"; -import { signup } from "../common/signup.js"; -import signin from "../common/signin.js"; - -export default async (ctx: Koa.Context) => { - const body = ctx.request.body; - - const code = body["code"]; - - try { - const pendingUser = await UserPendings.findOneByOrFail({ code }); - - const { account, secret } = await signup({ - username: pendingUser.username, - passwordHash: pendingUser.password, - }); - - UserPendings.delete({ - id: pendingUser.id, - }); - - const profile = await UserProfiles.findOneByOrFail({ userId: account.id }); - - await UserProfiles.update( - { userId: profile.userId }, - { - email: pendingUser.email, - emailVerified: true, - emailVerifyCode: null, - }, - ); - - signin(ctx, account); - } catch (e) { - ctx.throw(400, e); - } -}; diff --git a/packages/backend/src/server/api/private/signup.ts b/packages/backend/src/server/api/private/signup.ts deleted file mode 100644 index 754d86c3b8..0000000000 --- a/packages/backend/src/server/api/private/signup.ts +++ /dev/null @@ -1,123 +0,0 @@ -import type Koa from "koa"; -import rndstr from "rndstr"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { verifyHcaptcha, verifyRecaptcha } from "@/misc/captcha.js"; -import { Users, RegistrationTickets, UserPendings } from "@/models/index.js"; -import { signup } from "../common/signup.js"; -import config from "@/config/index.js"; -import { sendEmail } from "@/services/send-email.js"; -import { genId } from "@/misc/gen-id.js"; -import { validateEmailForAccount } from "@/services/validate-email-for-account.js"; -import { hashPassword } from "@/misc/password.js"; - -export default async (ctx: Koa.Context) => { - const body = ctx.request.body; - - const instance = await fetchMeta(true); - - // Verify *Captcha - // ただしテスト時はこの機構は障害となるため無効にする - if (process.env.NODE_ENV !== "test") { - if (instance.enableHcaptcha && instance.hcaptchaSecretKey) { - await verifyHcaptcha( - instance.hcaptchaSecretKey, - body["hcaptcha-response"], - ).catch((e) => { - ctx.throw(400, e); - }); - } - - if (instance.enableRecaptcha && instance.recaptchaSecretKey) { - await verifyRecaptcha( - instance.recaptchaSecretKey, - body["g-recaptcha-response"], - ).catch((e) => { - ctx.throw(400, e); - }); - } - } - - const username = body["username"]; - const password = body["password"]; - const host: string | null = - process.env.NODE_ENV === "test" ? body["host"] || null : null; - const invitationCode = body["invitationCode"]; - const emailAddress = body["emailAddress"]; - - if (instance.emailRequiredForSignup) { - if (emailAddress == null || typeof emailAddress !== "string") { - ctx.status = 400; - return; - } - - const available = await validateEmailForAccount(emailAddress); - if (!available) { - ctx.status = 400; - return; - } - } - - if (instance.disableRegistration) { - if (invitationCode == null || typeof invitationCode !== "string") { - ctx.status = 400; - return; - } - - const ticket = await RegistrationTickets.findOneBy({ - code: invitationCode, - }); - - if (ticket == null) { - ctx.status = 400; - return; - } - - RegistrationTickets.delete(ticket.id); - } - - if (instance.emailRequiredForSignup) { - const code = rndstr("a-z0-9", 16); - - // Generate hash of password - const hash = await hashPassword(password); - - await UserPendings.insert({ - id: genId(), - createdAt: new Date(), - code, - email: emailAddress, - username: username, - password: hash, - }); - - const link = `${config.url}/signup-complete/${code}`; - - sendEmail( - emailAddress, - "Signup", - `To complete signup, please click this link:<br><a href="${link}">${link}</a>`, - `To complete signup, please click this link: ${link}`, - ); - - ctx.status = 204; - } else { - try { - const { account, secret } = await signup({ - username, - password, - host, - }); - - const res = await Users.pack(account, account, { - detail: true, - includeSecrets: true, - }); - - (res as any).token = secret; - - ctx.body = res; - } catch (e) { - ctx.throw(400, e); - } - } -}; diff --git a/packages/backend/src/server/api/service/discord.ts b/packages/backend/src/server/api/service/discord.ts deleted file mode 100644 index 9906d2f7ca..0000000000 --- a/packages/backend/src/server/api/service/discord.ts +++ /dev/null @@ -1,333 +0,0 @@ -import type Koa from "koa"; -import Router from "@koa/router"; -import { OAuth2 } from "oauth"; -import { v4 as uuid } from "uuid"; -import { IsNull } from "typeorm"; -import { getJson } from "@/misc/fetch.js"; -import config from "@/config/index.js"; -import { publishMainStream } from "@/services/stream.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { Users, UserProfiles } from "@/models/index.js"; -import type { ILocalUser } from "@/models/entities/user.js"; -import { redisClient } from "../../../db/redis.js"; -import signin from "../common/signin.js"; - -function getUserToken(ctx: Koa.BaseContext): string | null { - return ((ctx.headers["cookie"] || "").match(/igi=(\w+)/) || [null, null])[1]; -} - -function compareOrigin(ctx: Koa.BaseContext): boolean { - function normalizeUrl(url?: string): string { - return url ? (url.endsWith("/") ? url.substr(0, url.length - 1) : url) : ""; - } - - const referer = ctx.headers["referer"]; - - return normalizeUrl(referer) === normalizeUrl(config.url); -} - -// Init router -const router = new Router(); - -router.get("/disconnect/discord", async (ctx) => { - if (!compareOrigin(ctx)) { - ctx.throw(400, "invalid origin"); - return; - } - - const userToken = getUserToken(ctx); - if (!userToken) { - ctx.throw(400, "signin required"); - return; - } - - const user = await Users.findOneByOrFail({ - host: IsNull(), - token: userToken, - }); - - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - profile.integrations.discord = undefined; - - await UserProfiles.update(user.id, { - integrations: profile.integrations, - }); - - ctx.body = "Discordの連携を解除しました :v:"; - - // Publish i updated event - publishMainStream( - user.id, - "meUpdated", - await Users.pack(user, user, { - detail: true, - includeSecrets: true, - }), - ); -}); - -async function getOAuth2() { - const meta = await fetchMeta(true); - - if (meta.enableDiscordIntegration) { - return new OAuth2( - meta.discordClientId!, - meta.discordClientSecret!, - "https://discord.com/", - "api/oauth2/authorize", - "api/oauth2/token", - ); - } else { - return null; - } -} - -router.get("/connect/discord", async (ctx) => { - if (!compareOrigin(ctx)) { - ctx.throw(400, "invalid origin"); - return; - } - - const userToken = getUserToken(ctx); - if (!userToken) { - ctx.throw(400, "signin required"); - return; - } - - const params = { - redirect_uri: `${config.url}/api/dc/cb`, - scope: ["identify"], - state: uuid(), - response_type: "code", - }; - - redisClient.set(userToken, JSON.stringify(params)); - - const oauth2 = await getOAuth2(); - ctx.redirect(oauth2!.getAuthorizeUrl(params)); -}); - -router.get("/signin/discord", async (ctx) => { - const sessid = uuid(); - - const params = { - redirect_uri: `${config.url}/api/dc/cb`, - scope: ["identify"], - state: uuid(), - response_type: "code", - }; - - ctx.cookies.set("signin_with_discord_sid", sessid, { - path: "/", - secure: config.url.startsWith("https"), - httpOnly: true, - }); - - redisClient.set(sessid, JSON.stringify(params)); - - const oauth2 = await getOAuth2(); - ctx.redirect(oauth2!.getAuthorizeUrl(params)); -}); - -router.get("/dc/cb", async (ctx) => { - const userToken = getUserToken(ctx); - - const oauth2 = await getOAuth2(); - - if (!userToken) { - const sessid = ctx.cookies.get("signin_with_discord_sid"); - - if (!sessid) { - ctx.throw(400, "invalid session"); - return; - } - - const code = ctx.query.code; - - if (!code || typeof code !== "string") { - ctx.throw(400, "invalid session"); - return; - } - - const { redirect_uri, state } = await new Promise<any>((res, rej) => { - redisClient.get(sessid, async (_, state) => { - res(JSON.parse(state)); - }); - }); - - if (ctx.query.state !== state) { - ctx.throw(400, "invalid session"); - return; - } - - const { accessToken, refreshToken, expiresDate } = await new Promise<any>( - (res, rej) => - oauth2!.getOAuthAccessToken( - code, - { - grant_type: "authorization_code", - redirect_uri, - }, - (err, accessToken, refreshToken, result) => { - if (err) { - rej(err); - } else if (result.error) { - rej(result.error); - } else { - res({ - accessToken, - refreshToken, - expiresDate: Date.now() + Number(result.expires_in) * 1000, - }); - } - }, - ), - ); - - const { id, username, discriminator } = (await getJson( - "https://discord.com/api/users/@me", - "*/*", - 10 * 1000, - { - Authorization: `Bearer ${accessToken}`, - }, - )) as Record<string, unknown>; - - if ( - typeof id !== "string" || - typeof username !== "string" || - typeof discriminator !== "string" - ) { - ctx.throw(400, "invalid session"); - return; - } - - const profile = await UserProfiles.createQueryBuilder() - .where("\"integrations\"->'discord'->>'id' = :id", { id: id }) - .andWhere('"userHost" IS NULL') - .getOne(); - - if (profile == null) { - ctx.throw( - 404, - `@${username}#${discriminator}と連携しているMisskeyアカウントはありませんでした...`, - ); - return; - } - - await UserProfiles.update(profile.userId, { - integrations: { - ...profile.integrations, - discord: { - id: id, - accessToken: accessToken, - refreshToken: refreshToken, - expiresDate: expiresDate, - username: username, - discriminator: discriminator, - }, - }, - }); - - signin( - ctx, - (await Users.findOneBy({ id: profile.userId })) as ILocalUser, - true, - ); - } else { - const code = ctx.query.code; - - if (!code || typeof code !== "string") { - ctx.throw(400, "invalid session"); - return; - } - - const { redirect_uri, state } = await new Promise<any>((res, rej) => { - redisClient.get(userToken, async (_, state) => { - res(JSON.parse(state)); - }); - }); - - if (ctx.query.state !== state) { - ctx.throw(400, "invalid session"); - return; - } - - const { accessToken, refreshToken, expiresDate } = await new Promise<any>( - (res, rej) => - oauth2!.getOAuthAccessToken( - code, - { - grant_type: "authorization_code", - redirect_uri, - }, - (err, accessToken, refreshToken, result) => { - if (err) { - rej(err); - } else if (result.error) { - rej(result.error); - } else { - res({ - accessToken, - refreshToken, - expiresDate: Date.now() + Number(result.expires_in) * 1000, - }); - } - }, - ), - ); - - const { id, username, discriminator } = (await getJson( - "https://discord.com/api/users/@me", - "*/*", - 10 * 1000, - { - Authorization: `Bearer ${accessToken}`, - }, - )) as Record<string, unknown>; - if ( - typeof id !== "string" || - typeof username !== "string" || - typeof discriminator !== "string" - ) { - ctx.throw(400, "invalid session"); - return; - } - - const user = await Users.findOneByOrFail({ - host: IsNull(), - token: userToken, - }); - - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - await UserProfiles.update(user.id, { - integrations: { - ...profile.integrations, - discord: { - accessToken: accessToken, - refreshToken: refreshToken, - expiresDate: expiresDate, - id: id, - username: username, - discriminator: discriminator, - }, - }, - }); - - ctx.body = `Discord: @${username}#${discriminator} を、Misskey: @${user.username} に接続しました!`; - - // Publish i updated event - publishMainStream( - user.id, - "meUpdated", - await Users.pack(user, user, { - detail: true, - includeSecrets: true, - }), - ); - } -}); - -export default router; diff --git a/packages/backend/src/server/api/service/github.ts b/packages/backend/src/server/api/service/github.ts deleted file mode 100644 index f77c5f795d..0000000000 --- a/packages/backend/src/server/api/service/github.ts +++ /dev/null @@ -1,296 +0,0 @@ -import type Koa from "koa"; -import Router from "@koa/router"; -import { OAuth2 } from "oauth"; -import { v4 as uuid } from "uuid"; -import { IsNull } from "typeorm"; -import { getJson } from "@/misc/fetch.js"; -import config from "@/config/index.js"; -import { publishMainStream } from "@/services/stream.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { Users, UserProfiles } from "@/models/index.js"; -import type { ILocalUser } from "@/models/entities/user.js"; -import { redisClient } from "../../../db/redis.js"; -import signin from "../common/signin.js"; - -function getUserToken(ctx: Koa.BaseContext): string | null { - return ((ctx.headers["cookie"] || "").match(/igi=(\w+)/) || [null, null])[1]; -} - -function compareOrigin(ctx: Koa.BaseContext): boolean { - function normalizeUrl(url?: string): string { - return url ? (url.endsWith("/") ? url.substr(0, url.length - 1) : url) : ""; - } - - const referer = ctx.headers["referer"]; - - return normalizeUrl(referer) === normalizeUrl(config.url); -} - -// Init router -const router = new Router(); - -router.get("/disconnect/github", async (ctx) => { - if (!compareOrigin(ctx)) { - ctx.throw(400, "invalid origin"); - return; - } - - const userToken = getUserToken(ctx); - if (!userToken) { - ctx.throw(400, "signin required"); - return; - } - - const user = await Users.findOneByOrFail({ - host: IsNull(), - token: userToken, - }); - - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - profile.integrations.github = undefined; - - await UserProfiles.update(user.id, { - integrations: profile.integrations, - }); - - ctx.body = "GitHubの連携を解除しました :v:"; - - // Publish i updated event - publishMainStream( - user.id, - "meUpdated", - await Users.pack(user, user, { - detail: true, - includeSecrets: true, - }), - ); -}); - -async function getOath2() { - const meta = await fetchMeta(true); - - if ( - meta.enableGithubIntegration && - meta.githubClientId && - meta.githubClientSecret - ) { - return new OAuth2( - meta.githubClientId, - meta.githubClientSecret, - "https://github.com/", - "login/oauth/authorize", - "login/oauth/access_token", - ); - } else { - return null; - } -} - -router.get("/connect/github", async (ctx) => { - if (!compareOrigin(ctx)) { - ctx.throw(400, "invalid origin"); - return; - } - - const userToken = getUserToken(ctx); - if (!userToken) { - ctx.throw(400, "signin required"); - return; - } - - const params = { - redirect_uri: `${config.url}/api/gh/cb`, - scope: ["read:user"], - state: uuid(), - }; - - redisClient.set(userToken, JSON.stringify(params)); - - const oauth2 = await getOath2(); - ctx.redirect(oauth2!.getAuthorizeUrl(params)); -}); - -router.get("/signin/github", async (ctx) => { - const sessid = uuid(); - - const params = { - redirect_uri: `${config.url}/api/gh/cb`, - scope: ["read:user"], - state: uuid(), - }; - - ctx.cookies.set("signin_with_github_sid", sessid, { - path: "/", - secure: config.url.startsWith("https"), - httpOnly: true, - }); - - redisClient.set(sessid, JSON.stringify(params)); - - const oauth2 = await getOath2(); - ctx.redirect(oauth2!.getAuthorizeUrl(params)); -}); - -router.get("/gh/cb", async (ctx) => { - const userToken = getUserToken(ctx); - - const oauth2 = await getOath2(); - - if (!userToken) { - const sessid = ctx.cookies.get("signin_with_github_sid"); - - if (!sessid) { - ctx.throw(400, "invalid session"); - return; - } - - const code = ctx.query.code; - - if (!code || typeof code !== "string") { - ctx.throw(400, "invalid session"); - return; - } - - const { redirect_uri, state } = await new Promise<any>((res, rej) => { - redisClient.get(sessid, async (_, state) => { - res(JSON.parse(state)); - }); - }); - - if (ctx.query.state !== state) { - ctx.throw(400, "invalid session"); - return; - } - - const { accessToken } = await new Promise<any>((res, rej) => - oauth2!.getOAuthAccessToken( - code, - { - redirect_uri, - }, - (err, accessToken, refresh, result) => { - if (err) { - rej(err); - } else if (result.error) { - rej(result.error); - } else { - res({ accessToken }); - } - }, - ), - ); - - const { login, id } = (await getJson( - "https://api.github.com/user", - "application/vnd.github.v3+json", - 10 * 1000, - { - Authorization: `bearer ${accessToken}`, - }, - )) as Record<string, unknown>; - if (typeof login !== "string" || typeof id !== "string") { - ctx.throw(400, "invalid session"); - return; - } - - const link = await UserProfiles.createQueryBuilder() - .where("\"integrations\"->'github'->>'id' = :id", { id: id }) - .andWhere('"userHost" IS NULL') - .getOne(); - - if (link == null) { - ctx.throw( - 404, - `@${login}と連携しているMisskeyアカウントはありませんでした...`, - ); - return; - } - - signin( - ctx, - (await Users.findOneBy({ id: link.userId })) as ILocalUser, - true, - ); - } else { - const code = ctx.query.code; - - if (!code || typeof code !== "string") { - ctx.throw(400, "invalid session"); - return; - } - - const { redirect_uri, state } = await new Promise<any>((res, rej) => { - redisClient.get(userToken, async (_, state) => { - res(JSON.parse(state)); - }); - }); - - if (ctx.query.state !== state) { - ctx.throw(400, "invalid session"); - return; - } - - const { accessToken } = await new Promise<any>((res, rej) => - oauth2!.getOAuthAccessToken( - code, - { redirect_uri }, - (err, accessToken, refresh, result) => { - if (err) { - rej(err); - } else if (result.error) { - rej(result.error); - } else { - res({ accessToken }); - } - }, - ), - ); - - const { login, id } = (await getJson( - "https://api.github.com/user", - "application/vnd.github.v3+json", - 10 * 1000, - { - Authorization: `bearer ${accessToken}`, - }, - )) as Record<string, unknown>; - - if (typeof login !== "string" || typeof id !== "string") { - ctx.throw(400, "invalid session"); - return; - } - - const user = await Users.findOneByOrFail({ - host: IsNull(), - token: userToken, - }); - - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - await UserProfiles.update(user.id, { - integrations: { - ...profile.integrations, - github: { - accessToken: accessToken, - id: id, - login: login, - }, - }, - }); - - ctx.body = `GitHub: @${login} を、Misskey: @${user.username} に接続しました!`; - - // Publish i updated event - publishMainStream( - user.id, - "meUpdated", - await Users.pack(user, user, { - detail: true, - includeSecrets: true, - }), - ); - } -}); - -export default router; diff --git a/packages/backend/src/server/api/service/twitter.ts b/packages/backend/src/server/api/service/twitter.ts deleted file mode 100644 index 3695592410..0000000000 --- a/packages/backend/src/server/api/service/twitter.ts +++ /dev/null @@ -1,226 +0,0 @@ -import type Koa from "koa"; -import Router from "@koa/router"; -import { v4 as uuid } from "uuid"; -import autwh from "autwh"; -import { IsNull } from "typeorm"; -import { publishMainStream } from "@/services/stream.js"; -import config from "@/config/index.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { Users, UserProfiles } from "@/models/index.js"; -import type { ILocalUser } from "@/models/entities/user.js"; -import signin from "../common/signin.js"; -import { redisClient } from "../../../db/redis.js"; - -function getUserToken(ctx: Koa.BaseContext): string | null { - return ((ctx.headers["cookie"] || "").match(/igi=(\w+)/) || [null, null])[1]; -} - -function compareOrigin(ctx: Koa.BaseContext): boolean { - function normalizeUrl(url?: string): string { - return url == null - ? "" - : url.endsWith("/") - ? url.substr(0, url.length - 1) - : url; - } - - const referer = ctx.headers["referer"]; - - return normalizeUrl(referer) === normalizeUrl(config.url); -} - -// Init router -const router = new Router(); - -router.get("/disconnect/twitter", async (ctx) => { - if (!compareOrigin(ctx)) { - ctx.throw(400, "invalid origin"); - return; - } - - const userToken = getUserToken(ctx); - if (userToken == null) { - ctx.throw(400, "signin required"); - return; - } - - const user = await Users.findOneByOrFail({ - host: IsNull(), - token: userToken, - }); - - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - profile.integrations.twitter = undefined; - - await UserProfiles.update(user.id, { - integrations: profile.integrations, - }); - - ctx.body = "Twitterの連携を解除しました :v:"; - - // Publish i updated event - publishMainStream( - user.id, - "meUpdated", - await Users.pack(user, user, { - detail: true, - includeSecrets: true, - }), - ); -}); - -async function getTwAuth() { - const meta = await fetchMeta(true); - - if ( - meta.enableTwitterIntegration && - meta.twitterConsumerKey && - meta.twitterConsumerSecret - ) { - return autwh({ - consumerKey: meta.twitterConsumerKey, - consumerSecret: meta.twitterConsumerSecret, - callbackUrl: `${config.url}/api/tw/cb`, - }); - } else { - return null; - } -} - -router.get("/connect/twitter", async (ctx) => { - if (!compareOrigin(ctx)) { - ctx.throw(400, "invalid origin"); - return; - } - - const userToken = getUserToken(ctx); - if (userToken == null) { - ctx.throw(400, "signin required"); - return; - } - - const twAuth = await getTwAuth(); - const twCtx = await twAuth!.begin(); - redisClient.set(userToken, JSON.stringify(twCtx)); - ctx.redirect(twCtx.url); -}); - -router.get("/signin/twitter", async (ctx) => { - const twAuth = await getTwAuth(); - const twCtx = await twAuth!.begin(); - - const sessid = uuid(); - - redisClient.set(sessid, JSON.stringify(twCtx)); - - ctx.cookies.set("signin_with_twitter_sid", sessid, { - path: "/", - secure: config.url.startsWith("https"), - httpOnly: true, - }); - - ctx.redirect(twCtx.url); -}); - -router.get("/tw/cb", async (ctx) => { - const userToken = getUserToken(ctx); - - const twAuth = await getTwAuth(); - - if (userToken == null) { - const sessid = ctx.cookies.get("signin_with_twitter_sid"); - - if (sessid == null) { - ctx.throw(400, "invalid session"); - return; - } - - const get = new Promise<any>((res, rej) => { - redisClient.get(sessid, async (_, twCtx) => { - res(twCtx); - }); - }); - - const twCtx = await get; - - const verifier = ctx.query.oauth_verifier; - if (!verifier || typeof verifier !== "string") { - ctx.throw(400, "invalid session"); - return; - } - - const result = await twAuth!.done(JSON.parse(twCtx), verifier); - - const link = await UserProfiles.createQueryBuilder() - .where("\"integrations\"->'twitter'->>'userId' = :id", { - id: result.userId, - }) - .andWhere('"userHost" IS NULL') - .getOne(); - - if (link == null) { - ctx.throw( - 404, - `@${result.screenName}と連携しているMisskeyアカウントはありませんでした...`, - ); - return; - } - - signin( - ctx, - (await Users.findOneBy({ id: link.userId })) as ILocalUser, - true, - ); - } else { - const verifier = ctx.query.oauth_verifier; - - if (!verifier || typeof verifier !== "string") { - ctx.throw(400, "invalid session"); - return; - } - - const get = new Promise<any>((res, rej) => { - redisClient.get(userToken, async (_, twCtx) => { - res(twCtx); - }); - }); - - const twCtx = await get; - - const result = await twAuth!.done(JSON.parse(twCtx), verifier); - - const user = await Users.findOneByOrFail({ - host: IsNull(), - token: userToken, - }); - - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - await UserProfiles.update(user.id, { - integrations: { - ...profile.integrations, - twitter: { - accessToken: result.accessToken, - accessTokenSecret: result.accessTokenSecret, - userId: result.userId, - screenName: result.screenName, - }, - }, - }); - - ctx.body = `Twitter: @${result.screenName} を、Misskey: @${user.username} に接続しました!`; - - // Publish i updated event - publishMainStream( - user.id, - "meUpdated", - await Users.pack(user, user, { - detail: true, - includeSecrets: true, - }), - ); - } -}); - -export default router; diff --git a/packages/backend/src/server/api/stream/channel.ts b/packages/backend/src/server/api/stream/channel.ts deleted file mode 100644 index fc8e0ce35e..0000000000 --- a/packages/backend/src/server/api/stream/channel.ts +++ /dev/null @@ -1,99 +0,0 @@ -import type Connection from "."; -import type { Note } from "@/models/entities/note.js"; -import { Notes } from "@/models/index.js"; -import type { Packed } from "@/misc/schema.js"; -import { IdentifiableError } from "@/misc/identifiable-error.js"; - -/** - * Stream channel - */ -export default abstract class Channel { - protected connection: Connection; - public id: string; - public abstract readonly chName: string; - public static readonly shouldShare: boolean; - public static readonly requireCredential: boolean; - - protected get user() { - return this.connection.user; - } - - protected get userProfile() { - return this.connection.userProfile; - } - - protected get following() { - return this.connection.following; - } - - protected get muting() { - return this.connection.muting; - } - - protected get renoteMuting() { - return this.connection.renoteMuting; - } - - protected get blocking() { - return this.connection.blocking; - } - - protected get followingChannels() { - return this.connection.followingChannels; - } - - protected get subscriber() { - return this.connection.subscriber; - } - - constructor(id: string, connection: Connection) { - this.id = id; - this.connection = connection; - } - - public send(typeOrPayload: any, payload?: any) { - const type = payload === undefined ? typeOrPayload.type : typeOrPayload; - const body = payload === undefined ? typeOrPayload.body : payload; - - this.connection.sendMessageToWs("channel", { - id: this.id, - type: type, - body: body, - }); - } - - protected withPackedNote( - callback: (note: Packed<"Note">) => void, - ): (Note) => void { - return async (note: Note) => { - try { - // because `note` was previously JSON.stringify'ed, the fields that - // were objects before are now strings and have to be restored or - // removed from the object - note.createdAt = new Date(note.createdAt); - note.reply = undefined; - note.renote = undefined; - note.user = undefined; - note.channel = undefined; - - const packed = await Notes.pack(note, this.user, { detail: true }); - - callback(packed); - } catch (err) { - if ( - err instanceof IdentifiableError && - err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24" - ) { - // skip: note not visible to user - return; - } else { - throw err; - } - } - }; - } - - public abstract init(params: any): void; - public dispose?(): void; - public onMessage?(type: string, body: any): void; -} diff --git a/packages/backend/src/server/api/stream/channels/admin.ts b/packages/backend/src/server/api/stream/channels/admin.ts deleted file mode 100644 index 59ae228250..0000000000 --- a/packages/backend/src/server/api/stream/channels/admin.ts +++ /dev/null @@ -1,14 +0,0 @@ -import Channel from "../channel.js"; - -export default class extends Channel { - public readonly chName = "admin"; - public static shouldShare = true; - public static requireCredential = true; - - public async init(params: any) { - // Subscribe admin stream - this.subscriber.on(`adminStream:${this.user!.id}`, (data) => { - this.send(data); - }); - } -} diff --git a/packages/backend/src/server/api/stream/channels/antenna.ts b/packages/backend/src/server/api/stream/channels/antenna.ts deleted file mode 100644 index 050a8d1019..0000000000 --- a/packages/backend/src/server/api/stream/channels/antenna.ts +++ /dev/null @@ -1,63 +0,0 @@ -import Channel from "../channel.js"; -import { Notes } from "@/models/index.js"; -import { isUserRelated } from "@/misc/is-user-related.js"; -import type { StreamMessages } from "../types.js"; -import { IdentifiableError } from "@/misc/identifiable-error.js"; - -export default class extends Channel { - public readonly chName = "antenna"; - public static shouldShare = false; - public static requireCredential = false; - private antennaId: string; - - constructor(id: string, connection: Channel["connection"]) { - super(id, connection); - this.onEvent = this.onEvent.bind(this); - } - - public async init(params: any) { - this.antennaId = params.antennaId as string; - - // Subscribe stream - this.subscriber.on(`antennaStream:${this.antennaId}`, this.onEvent); - } - - private async onEvent(data: StreamMessages["antenna"]["payload"]) { - if (data.type === "note") { - try { - const note = await Notes.pack(data.body.id, this.user, { - detail: true, - }); - - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.muting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.blocking)) return; - - if (note.renote && !note.text && isUserRelated(note, this.renoteMuting)) - return; - - this.connection.cacheNote(note); - - this.send("note", note); - } catch (e) { - if ( - e instanceof IdentifiableError && - e.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24" - ) { - // skip: note not visible to user - return; - } else { - throw e; - } - } - } else { - this.send(data.type, data.body); - } - } - - public dispose() { - // Unsubscribe events - this.subscriber.off(`antennaStream:${this.antennaId}`, this.onEvent); - } -} diff --git a/packages/backend/src/server/api/stream/channels/channel.ts b/packages/backend/src/server/api/stream/channels/channel.ts deleted file mode 100644 index d046579f42..0000000000 --- a/packages/backend/src/server/api/stream/channels/channel.ts +++ /dev/null @@ -1,84 +0,0 @@ -import Channel from "../channel.js"; -import { Users } from "@/models/index.js"; -import { isUserRelated } from "@/misc/is-user-related.js"; -import type { User } from "@/models/entities/user.js"; -import type { StreamMessages } from "../types.js"; -import type { Packed } from "@/misc/schema.js"; - -export default class extends Channel { - public readonly chName = "channel"; - public static shouldShare = false; - public static requireCredential = false; - private channelId: string; - private typers: Map<User["id"], Date> = new Map(); - private emitTypersIntervalId: ReturnType<typeof setInterval>; - - constructor(id: string, connection: Channel["connection"]) { - super(id, connection); - this.onNote = this.onNote.bind(this); - this.emitTypers = this.emitTypers.bind(this); - } - - public async init(params: any) { - this.channelId = params.channelId as string; - - // Subscribe stream - this.subscriber.on("notesStream", this.onNote); - this.subscriber.on(`channelStream:${this.channelId}`, this.onEvent); - this.emitTypersIntervalId = setInterval(this.emitTypers, 5000); - } - - private async onNote(note: Packed<"Note">) { - if (note.channelId !== this.channelId) return; - - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.muting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.blocking)) return; - - if (note.renote && !note.text && isUserRelated(note, this.renoteMuting)) - return; - - this.connection.cacheNote(note); - - this.send("note", note); - } - - private onEvent(data: StreamMessages["channel"]["payload"]) { - if (data.type === "typing") { - const id = data.body; - const begin = !this.typers.has(id); - this.typers.set(id, new Date()); - if (begin) { - this.emitTypers(); - } - } - } - - private async emitTypers() { - const now = new Date(); - - // Remove not typing users - for (const [userId, date] of Object.entries(this.typers)) { - if (now.getTime() - date.getTime() > 5000) this.typers.delete(userId); - } - - const userIds = Array.from(this.typers.keys()); - const users = await Users.packMany(userIds, null, { - detail: false, - }); - - this.send({ - type: "typers", - body: users, - }); - } - - public dispose() { - // Unsubscribe events - this.subscriber.off("notesStream", this.onNote); - this.subscriber.off(`channelStream:${this.channelId}`, this.onEvent); - - clearInterval(this.emitTypersIntervalId); - } -} diff --git a/packages/backend/src/server/api/stream/channels/drive.ts b/packages/backend/src/server/api/stream/channels/drive.ts deleted file mode 100644 index 275730eae5..0000000000 --- a/packages/backend/src/server/api/stream/channels/drive.ts +++ /dev/null @@ -1,14 +0,0 @@ -import Channel from "../channel.js"; - -export default class extends Channel { - public readonly chName = "drive"; - public static shouldShare = true; - public static requireCredential = true; - - public async init(params: any) { - // Subscribe drive stream - this.subscriber.on(`driveStream:${this.user!.id}`, (data) => { - this.send(data); - }); - } -} diff --git a/packages/backend/src/server/api/stream/channels/global-timeline.ts b/packages/backend/src/server/api/stream/channels/global-timeline.ts deleted file mode 100644 index aa3844c7e3..0000000000 --- a/packages/backend/src/server/api/stream/channels/global-timeline.ts +++ /dev/null @@ -1,82 +0,0 @@ -import Channel from "../channel.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { getWordMute } from "@/misc/check-word-mute.js"; -import { isInstanceMuted } from "@/misc/is-instance-muted.js"; -import { isUserRelated } from "@/misc/is-user-related.js"; -import type { Packed } from "@/misc/schema.js"; - -export default class extends Channel { - public readonly chName = "globalTimeline"; - public static shouldShare = true; - public static requireCredential = false; - - constructor(id: string, connection: Channel["connection"]) { - super(id, connection); - this.onNote = this.withPackedNote(this.onNote.bind(this)); - } - - public async init(params: any) { - const meta = await fetchMeta(); - if (meta.disableGlobalTimeline) { - if (this.user == null || !(this.user.isAdmin || this.user.isModerator)) - return; - } - - // Subscribe events - this.subscriber.on("notesStream", this.onNote); - } - - private async onNote(note: Packed<"Note">) { - if (note.visibility !== "public") return; - if (note.channelId != null) return; - - // 関係ない返信は除外 - if (note.reply && !this.user!.showTimelineReplies) { - const reply = note.reply; - // 「チャンネル接続主への返信」でもなければ、「チャンネル接続主が行った返信」でもなければ、「投稿者の投稿者自身への返信」でもない場合 - if ( - reply.userId !== this.user!.id && - note.userId !== this.user!.id && - reply.userId !== note.userId - ) - return; - } - - // Ignore notes from instances the user has muted - if ( - isInstanceMuted( - note, - new Set<string>(this.userProfile?.mutedInstances ?? []), - ) - ) - return; - - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.muting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.blocking)) return; - - if (note.renote && !note.text && isUserRelated(note, this.renoteMuting)) - return; - - // 流れてきたNoteがミュートすべきNoteだったら無視する - // TODO: 将来的には、単にMutedNoteテーブルにレコードがあるかどうかで判定したい(以下の理由により難しそうではある) - // 現状では、ワードミュートにおけるMutedNoteレコードの追加処理はストリーミングに流す処理と並列で行われるため、 - // レコードが追加されるNoteでも追加されるより先にここのストリーミングの処理に到達することが起こる。 - // そのためレコードが存在するかのチェックでは不十分なので、改めてgetWordMuteを呼んでいる - if ( - this.userProfile && - (await getWordMute(note, this.user, this.userProfile.mutedWords)).muted - ) - return; - - this.connection.cacheNote(note); - - this.send("note", note); - } - - public dispose() { - // Unsubscribe events - this.subscriber.off("notesStream", this.onNote); - } -} diff --git a/packages/backend/src/server/api/stream/channels/hashtag.ts b/packages/backend/src/server/api/stream/channels/hashtag.ts deleted file mode 100644 index a2e5481abb..0000000000 --- a/packages/backend/src/server/api/stream/channels/hashtag.ts +++ /dev/null @@ -1,52 +0,0 @@ -import Channel from "../channel.js"; -import { normalizeForSearch } from "@/misc/normalize-for-search.js"; -import { isUserRelated } from "@/misc/is-user-related.js"; -import type { Packed } from "@/misc/schema.js"; - -export default class extends Channel { - public readonly chName = "hashtag"; - public static shouldShare = false; - public static requireCredential = false; - private q: string[][]; - - constructor(id: string, connection: Channel["connection"]) { - super(id, connection); - this.onNote = this.withPackedNote(this.onNote.bind(this)); - } - - public async init(params: any) { - this.q = params.q; - - if (this.q == null) return; - - // Subscribe stream - this.subscriber.on("notesStream", this.onNote); - } - - private async onNote(note: Packed<"Note">) { - const noteTags = note.tags - ? note.tags.map((t: string) => t.toLowerCase()) - : []; - const matched = this.q.some((tags) => - tags.every((tag) => noteTags.includes(normalizeForSearch(tag))), - ); - if (!matched) return; - - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.muting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.blocking)) return; - - if (note.renote && !note.text && isUserRelated(note, this.renoteMuting)) - return; - - this.connection.cacheNote(note); - - this.send("note", note); - } - - public dispose() { - // Unsubscribe events - this.subscriber.off("notesStream", this.onNote); - } -} diff --git a/packages/backend/src/server/api/stream/channels/home-timeline.ts b/packages/backend/src/server/api/stream/channels/home-timeline.ts deleted file mode 100644 index fa4a8a3901..0000000000 --- a/packages/backend/src/server/api/stream/channels/home-timeline.ts +++ /dev/null @@ -1,80 +0,0 @@ -import Channel from "../channel.js"; -import { getWordMute } from "@/misc/check-word-mute.js"; -import { isUserRelated } from "@/misc/is-user-related.js"; -import { isInstanceMuted } from "@/misc/is-instance-muted.js"; -import type { Packed } from "@/misc/schema.js"; - -export default class extends Channel { - public readonly chName = "homeTimeline"; - public static shouldShare = true; - public static requireCredential = true; - - constructor(id: string, connection: Channel["connection"]) { - super(id, connection); - this.onNote = this.withPackedNote(this.onNote.bind(this)); - } - - public async init(params: any) { - // Subscribe events - this.subscriber.on("notesStream", this.onNote); - } - - private async onNote(note: Packed<"Note">) { - if (note.channelId) { - if (!this.followingChannels.has(note.channelId)) return; - } else { - // その投稿のユーザーをフォローしていなかったら弾く - if (this.user!.id !== note.userId && !this.following.has(note.userId)) - return; - } - - // Ignore notes from instances the user has muted - if ( - isInstanceMuted( - note, - new Set<string>(this.userProfile?.mutedInstances ?? []), - ) - ) - return; - - // 関係ない返信は除外 - if (note.reply && !this.user!.showTimelineReplies) { - const reply = note.reply; - // 「チャンネル接続主への返信」でもなければ、「チャンネル接続主が行った返信」でもなければ、「投稿者の投稿者自身への返信」でもない場合 - if ( - reply.userId !== this.user!.id && - note.userId !== this.user!.id && - reply.userId !== note.userId - ) - return; - } - - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.muting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.blocking)) return; - - if (note.renote && !note.text && isUserRelated(note, this.renoteMuting)) - return; - - // 流れてきたNoteがミュートすべきNoteだったら無視する - // TODO: 将来的には、単にMutedNoteテーブルにレコードがあるかどうかで判定したい(以下の理由により難しそうではある) - // 現状では、ワードミュートにおけるMutedNoteレコードの追加処理はストリーミングに流す処理と並列で行われるため、 - // レコードが追加されるNoteでも追加されるより先にここのストリーミングの処理に到達することが起こる。 - // そのためレコードが存在するかのチェックでは不十分なので、改めてgetWordMuteを呼んでいる - if ( - this.userProfile && - (await getWordMute(note, this.user, this.userProfile.mutedWords)).muted - ) - return; - - this.connection.cacheNote(note); - - this.send("note", note); - } - - public dispose() { - // Unsubscribe events - this.subscriber.off("notesStream", this.onNote); - } -} diff --git a/packages/backend/src/server/api/stream/channels/hybrid-timeline.ts b/packages/backend/src/server/api/stream/channels/hybrid-timeline.ts deleted file mode 100644 index 557bb96827..0000000000 --- a/packages/backend/src/server/api/stream/channels/hybrid-timeline.ts +++ /dev/null @@ -1,97 +0,0 @@ -import Channel from "../channel.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { getWordMute } from "@/misc/check-word-mute.js"; -import { isUserRelated } from "@/misc/is-user-related.js"; -import { isInstanceMuted } from "@/misc/is-instance-muted.js"; -import type { Packed } from "@/misc/schema.js"; - -export default class extends Channel { - public readonly chName = "hybridTimeline"; - public static shouldShare = true; - public static requireCredential = true; - - constructor(id: string, connection: Channel["connection"]) { - super(id, connection); - this.onNote = this.withPackedNote(this.onNote.bind(this)); - } - - public async init(params: any) { - const meta = await fetchMeta(); - if ( - meta.disableLocalTimeline && - !this.user!.isAdmin && - !this.user!.isModerator - ) - return; - - // Subscribe events - this.subscriber.on("notesStream", this.onNote); - } - - private async onNote(note: Packed<"Note">) { - // チャンネルの投稿ではなく、自分自身の投稿 または - // チャンネルの投稿ではなく、その投稿のユーザーをフォローしている または - // チャンネルの投稿ではなく、全体公開のローカルの投稿 または - // フォローしているチャンネルの投稿 の場合だけ - if ( - !( - (note.channelId == null && this.user!.id === note.userId) || - (note.channelId == null && this.following.has(note.userId)) || - (note.channelId == null && - note.user.host == null && - note.visibility === "public") || - (note.channelId != null && this.followingChannels.has(note.channelId)) - ) - ) - return; - - // Ignore notes from instances the user has muted - if ( - isInstanceMuted( - note, - new Set<string>(this.userProfile?.mutedInstances ?? []), - ) - ) - return; - - // 関係ない返信は除外 - if (note.reply && !this.user!.showTimelineReplies) { - const reply = note.reply; - // 「チャンネル接続主への返信」でもなければ、「チャンネル接続主が行った返信」でもなければ、「投稿者の投稿者自身への返信」でもない場合 - if ( - reply.userId !== this.user!.id && - note.userId !== this.user!.id && - reply.userId !== note.userId - ) - return; - } - - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.muting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.blocking)) return; - - if (note.renote && !note.text && isUserRelated(note, this.renoteMuting)) - return; - - // 流れてきたNoteがミュートすべきNoteだったら無視する - // TODO: 将来的には、単にMutedNoteテーブルにレコードがあるかどうかで判定したい(以下の理由により難しそうではある) - // 現状では、ワードミュートにおけるMutedNoteレコードの追加処理はストリーミングに流す処理と並列で行われるため、 - // レコードが追加されるNoteでも追加されるより先にここのストリーミングの処理に到達することが起こる。 - // そのためレコードが存在するかのチェックでは不十分なので、改めてgetWordMuteを呼んでいる - if ( - this.userProfile && - (await getWordMute(note, this.user, this.userProfile.mutedWords)).muted - ) - return; - - this.connection.cacheNote(note); - - this.send("note", note); - } - - public dispose() { - // Unsubscribe events - this.subscriber.off("notesStream", this.onNote); - } -} diff --git a/packages/backend/src/server/api/stream/channels/index.ts b/packages/backend/src/server/api/stream/channels/index.ts deleted file mode 100644 index d1127be47c..0000000000 --- a/packages/backend/src/server/api/stream/channels/index.ts +++ /dev/null @@ -1,35 +0,0 @@ -import main from "./main.js"; -import homeTimeline from "./home-timeline.js"; -import localTimeline from "./local-timeline.js"; -import hybridTimeline from "./hybrid-timeline.js"; -import recommendedTimeline from "./recommended-timeline.js"; -import globalTimeline from "./global-timeline.js"; -import serverStats from "./server-stats.js"; -import queueStats from "./queue-stats.js"; -import userList from "./user-list.js"; -import antenna from "./antenna.js"; -import messaging from "./messaging.js"; -import messagingIndex from "./messaging-index.js"; -import drive from "./drive.js"; -import hashtag from "./hashtag.js"; -import channel from "./channel.js"; -import admin from "./admin.js"; - -export default { - main, - homeTimeline, - localTimeline, - recommendedTimeline, - hybridTimeline, - globalTimeline, - serverStats, - queueStats, - userList, - antenna, - messaging, - messagingIndex, - drive, - hashtag, - channel, - admin, -}; diff --git a/packages/backend/src/server/api/stream/channels/local-timeline.ts b/packages/backend/src/server/api/stream/channels/local-timeline.ts deleted file mode 100644 index dc3aab8d7d..0000000000 --- a/packages/backend/src/server/api/stream/channels/local-timeline.ts +++ /dev/null @@ -1,74 +0,0 @@ -import Channel from "../channel.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { getWordMute } from "@/misc/check-word-mute.js"; -import { isUserRelated } from "@/misc/is-user-related.js"; -import type { Packed } from "@/misc/schema.js"; - -export default class extends Channel { - public readonly chName = "localTimeline"; - public static shouldShare = true; - public static requireCredential = false; - - constructor(id: string, connection: Channel["connection"]) { - super(id, connection); - this.onNote = this.withPackedNote(this.onNote.bind(this)); - } - - public async init(params: any) { - const meta = await fetchMeta(); - if (meta.disableLocalTimeline) { - if (this.user == null || !(this.user.isAdmin || this.user.isModerator)) - return; - } - - // Subscribe events - this.subscriber.on("notesStream", this.onNote); - } - - private async onNote(note: Packed<"Note">) { - if (note.user.host !== null) return; - if (note.visibility !== "public") return; - if (note.channelId != null && !this.followingChannels.has(note.channelId)) - return; - - // 関係ない返信は除外 - if (note.reply && !this.user!.showTimelineReplies) { - const reply = note.reply; - // 「チャンネル接続主への返信」でもなければ、「チャンネル接続主が行った返信」でもなければ、「投稿者の投稿者自身への返信」でもない場合 - if ( - reply.userId !== this.user!.id && - note.userId !== this.user!.id && - reply.userId !== note.userId - ) - return; - } - - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.muting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.blocking)) return; - - if (note.renote && !note.text && isUserRelated(note, this.renoteMuting)) - return; - - // 流れてきたNoteがミュートすべきNoteだったら無視する - // TODO: 将来的には、単にMutedNoteテーブルにレコードがあるかどうかで判定したい(以下の理由により難しそうではある) - // 現状では、ワードミュートにおけるMutedNoteレコードの追加処理はストリーミングに流す処理と並列で行われるため、 - // レコードが追加されるNoteでも追加されるより先にここのストリーミングの処理に到達することが起こる。 - // そのためレコードが存在するかのチェックでは不十分なので、改めてgetWordMuteを呼んでいる - if ( - this.userProfile && - (await getWordMute(note, this.user, this.userProfile.mutedWords)).muted - ) - return; - - this.connection.cacheNote(note); - - this.send("note", note); - } - - public dispose() { - // Unsubscribe events - this.subscriber.off("notesStream", this.onNote); - } -} diff --git a/packages/backend/src/server/api/stream/channels/main.ts b/packages/backend/src/server/api/stream/channels/main.ts deleted file mode 100644 index b8c72442ff..0000000000 --- a/packages/backend/src/server/api/stream/channels/main.ts +++ /dev/null @@ -1,46 +0,0 @@ -import Channel from "../channel.js"; -import { - isInstanceMuted, - isUserFromMutedInstance, -} from "@/misc/is-instance-muted.js"; - -export default class extends Channel { - public readonly chName = "main"; - public static shouldShare = true; - public static requireCredential = true; - - public async init(params: any) { - // Subscribe main stream channel - this.subscriber.on(`mainStream:${this.user!.id}`, async (data) => { - switch (data.type) { - case "notification": { - // Ignore notifications from instances the user has muted - if ( - isUserFromMutedInstance( - data.body, - new Set<string>(this.userProfile?.mutedInstances ?? []), - ) - ) - return; - if (data.body.userId && this.muting.has(data.body.userId)) return; - - break; - } - case "mention": { - if ( - isInstanceMuted( - data.body, - new Set<string>(this.userProfile?.mutedInstances ?? []), - ) - ) - return; - - if (this.muting.has(data.body.userId)) return; - break; - } - } - - this.send(data.type, data.body); - }); - } -} diff --git a/packages/backend/src/server/api/stream/channels/messaging-index.ts b/packages/backend/src/server/api/stream/channels/messaging-index.ts deleted file mode 100644 index 8165172d73..0000000000 --- a/packages/backend/src/server/api/stream/channels/messaging-index.ts +++ /dev/null @@ -1,14 +0,0 @@ -import Channel from "../channel.js"; - -export default class extends Channel { - public readonly chName = "messagingIndex"; - public static shouldShare = true; - public static requireCredential = true; - - public async init(params: any) { - // Subscribe messaging index stream - this.subscriber.on(`messagingIndexStream:${this.user!.id}`, (data) => { - this.send(data); - }); - } -} diff --git a/packages/backend/src/server/api/stream/channels/messaging.ts b/packages/backend/src/server/api/stream/channels/messaging.ts deleted file mode 100644 index 0622bd4649..0000000000 --- a/packages/backend/src/server/api/stream/channels/messaging.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { - readUserMessagingMessage, - readGroupMessagingMessage, - deliverReadActivity, -} from "../../common/read-messaging-message.js"; -import Channel from "../channel.js"; -import { UserGroupJoinings, Users, MessagingMessages } from "@/models/index.js"; -import type { User, ILocalUser, IRemoteUser } from "@/models/entities/user.js"; -import type { UserGroup } from "@/models/entities/user-group.js"; -import type { StreamMessages } from "../types.js"; - -export default class extends Channel { - public readonly chName = "messaging"; - public static shouldShare = false; - public static requireCredential = true; - - private otherpartyId: string | null; - private otherparty: User | null; - private groupId: string | null; - private subCh: - | `messagingStream:${User["id"]}-${User["id"]}` - | `messagingStream:${UserGroup["id"]}`; - private typers: Map<User["id"], Date> = new Map(); - private emitTypersIntervalId: ReturnType<typeof setInterval>; - - constructor(id: string, connection: Channel["connection"]) { - super(id, connection); - this.onEvent = this.onEvent.bind(this); - this.onMessage = this.onMessage.bind(this); - this.emitTypers = this.emitTypers.bind(this); - } - - public async init(params: any) { - this.otherpartyId = params.otherparty; - this.otherparty = this.otherpartyId - ? await Users.findOneByOrFail({ id: this.otherpartyId }) - : null; - this.groupId = params.group; - - // Check joining - if (this.groupId) { - const joining = await UserGroupJoinings.findOneBy({ - userId: this.user!.id, - userGroupId: this.groupId, - }); - - if (joining == null) { - return; - } - } - - this.emitTypersIntervalId = setInterval(this.emitTypers, 5000); - - this.subCh = this.otherpartyId - ? `messagingStream:${this.user!.id}-${this.otherpartyId}` - : `messagingStream:${this.groupId}`; - - // Subscribe messaging stream - this.subscriber.on(this.subCh, this.onEvent); - } - - private onEvent( - data: - | StreamMessages["messaging"]["payload"] - | StreamMessages["groupMessaging"]["payload"], - ) { - if (data.type === "typing") { - const id = data.body; - const begin = !this.typers.has(id); - this.typers.set(id, new Date()); - if (begin) { - this.emitTypers(); - } - } else { - this.send(data); - } - } - - public onMessage(type: string, body: any) { - switch (type) { - case "read": - if (this.otherpartyId) { - readUserMessagingMessage(this.user!.id, this.otherpartyId, [body.id]); - - // リモートユーザーからのメッセージだったら既読配信 - if ( - Users.isLocalUser(this.user!) && - Users.isRemoteUser(this.otherparty!) - ) { - MessagingMessages.findOneBy({ id: body.id }).then((message) => { - if (message) - deliverReadActivity( - this.user as ILocalUser, - this.otherparty as IRemoteUser, - message, - ); - }); - } - } else if (this.groupId) { - readGroupMessagingMessage(this.user!.id, this.groupId, [body.id]); - } - break; - } - } - - private async emitTypers() { - const now = new Date(); - - // Remove not typing users - for (const [userId, date] of this.typers.entries()) { - if (now.getTime() - date.getTime() > 5000) this.typers.delete(userId); - } - - const userIds = Array.from(this.typers.keys()); - const users = await Users.packMany(userIds, null, { - detail: false, - }); - - this.send({ - type: "typers", - body: users, - }); - } - - public dispose() { - this.subscriber.off(this.subCh, this.onEvent); - - clearInterval(this.emitTypersIntervalId); - } -} diff --git a/packages/backend/src/server/api/stream/channels/queue-stats.ts b/packages/backend/src/server/api/stream/channels/queue-stats.ts deleted file mode 100644 index a5a93c332e..0000000000 --- a/packages/backend/src/server/api/stream/channels/queue-stats.ts +++ /dev/null @@ -1,42 +0,0 @@ -import Xev from "xev"; -import Channel from "../channel.js"; - -const ev = new Xev(); - -export default class extends Channel { - public readonly chName = "queueStats"; - public static shouldShare = true; - public static requireCredential = false; - - constructor(id: string, connection: Channel["connection"]) { - super(id, connection); - this.onStats = this.onStats.bind(this); - this.onMessage = this.onMessage.bind(this); - } - - public async init(params: any) { - ev.addListener("queueStats", this.onStats); - } - - private onStats(stats: any) { - this.send("stats", stats); - } - - public onMessage(type: string, body: any) { - switch (type) { - case "requestLog": - ev.once(`queueStatsLog:${body.id}`, (statsLog) => { - this.send("statsLog", statsLog); - }); - ev.emit("requestQueueStatsLog", { - id: body.id, - length: body.length, - }); - break; - } - } - - public dispose() { - ev.removeListener("queueStats", this.onStats); - } -} diff --git a/packages/backend/src/server/api/stream/channels/recommended-timeline.ts b/packages/backend/src/server/api/stream/channels/recommended-timeline.ts deleted file mode 100644 index 6baec77442..0000000000 --- a/packages/backend/src/server/api/stream/channels/recommended-timeline.ts +++ /dev/null @@ -1,95 +0,0 @@ -import Channel from "../channel.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { getWordMute } from "@/misc/check-word-mute.js"; -import { isUserRelated } from "@/misc/is-user-related.js"; -import { isInstanceMuted } from "@/misc/is-instance-muted.js"; -import type { Packed } from "@/misc/schema.js"; - -export default class extends Channel { - public readonly chName = "recommendedTimeline"; - public static shouldShare = true; - public static requireCredential = true; - - constructor(id: string, connection: Channel["connection"]) { - super(id, connection); - this.onNote = this.withPackedNote(this.onNote.bind(this)); - } - - public async init(params: any) { - const meta = await fetchMeta(); - if ( - meta.disableRecommendedTimeline && - !this.user!.isAdmin && - !this.user!.isModerator - ) - return; - - // Subscribe events - this.subscriber.on("notesStream", this.onNote); - } - - private async onNote(note: Packed<"Note">) { - // チャンネルの投稿ではなく、自分自身の投稿 または - // チャンネルの投稿ではなく、その投稿のユーザーをフォローしている または - // チャンネルの投稿ではなく、全体公開のローカルの投稿 または - // フォローしているチャンネルの投稿 の場合だけ - const meta = await fetchMeta(); - if ( - !( - note.user.host != null && - meta.recommendedInstances.includes(note.user.host) && - note.visibility === "public" - ) - ) - return; - - // Ignore notes from instances the user has muted - if ( - isInstanceMuted( - note, - new Set<string>(this.userProfile?.mutedInstances ?? []), - ) - ) - return; - - // 関係ない返信は除外 - if (note.reply && !this.user!.showTimelineReplies) { - const reply = note.reply; - // 「チャンネル接続主への返信」でもなければ、「チャンネル接続主が行った返信」でもなければ、「投稿者の投稿者自身への返信」でもない場合 - if ( - reply.userId !== this.user!.id && - note.userId !== this.user!.id && - reply.userId !== note.userId - ) - return; - } - - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.muting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.blocking)) return; - - if (note.renote && !note.text && isUserRelated(note, this.renoteMuting)) - return; - - // 流れてきたNoteがミュートすべきNoteだったら無視する - // TODO: 将来的には、単にMutedNoteテーブルにレコードがあるかどうかで判定したい(以下の理由により難しそうではある) - // 現状では、ワードミュートにおけるMutedNoteレコードの追加処理はストリーミングに流す処理と並列で行われるため、 - // レコードが追加されるNoteでも追加されるより先にここのストリーミングの処理に到達することが起こる。 - // そのためレコードが存在するかのチェックでは不十分なので、改めてgetWordMuteを呼んでいる - if ( - this.userProfile && - (await getWordMute(note, this.user, this.userProfile.mutedWords)).muted - ) - return; - - this.connection.cacheNote(note); - - this.send("note", note); - } - - public dispose() { - // Unsubscribe events - this.subscriber.off("notesStream", this.onNote); - } -} diff --git a/packages/backend/src/server/api/stream/channels/server-stats.ts b/packages/backend/src/server/api/stream/channels/server-stats.ts deleted file mode 100644 index 58659138de..0000000000 --- a/packages/backend/src/server/api/stream/channels/server-stats.ts +++ /dev/null @@ -1,42 +0,0 @@ -import Xev from "xev"; -import Channel from "../channel.js"; - -const ev = new Xev(); - -export default class extends Channel { - public readonly chName = "serverStats"; - public static shouldShare = true; - public static requireCredential = false; - - constructor(id: string, connection: Channel["connection"]) { - super(id, connection); - this.onStats = this.onStats.bind(this); - this.onMessage = this.onMessage.bind(this); - } - - public async init(params: any) { - ev.addListener("serverStats", this.onStats); - } - - private onStats(stats: any) { - this.send("stats", stats); - } - - public onMessage(type: string, body: any) { - switch (type) { - case "requestLog": - ev.once(`serverStatsLog:${body.id}`, (statsLog) => { - this.send("statsLog", statsLog); - }); - ev.emit("requestServerStatsLog", { - id: body.id, - length: body.length, - }); - break; - } - } - - public dispose() { - ev.removeListener("serverStats", this.onStats); - } -} diff --git a/packages/backend/src/server/api/stream/channels/user-list.ts b/packages/backend/src/server/api/stream/channels/user-list.ts deleted file mode 100644 index 105c45955c..0000000000 --- a/packages/backend/src/server/api/stream/channels/user-list.ts +++ /dev/null @@ -1,72 +0,0 @@ -import Channel from "../channel.js"; -import { UserListJoinings, UserLists } from "@/models/index.js"; -import type { User } from "@/models/entities/user.js"; -import { isUserRelated } from "@/misc/is-user-related.js"; -import type { Packed } from "@/misc/schema.js"; - -export default class extends Channel { - public readonly chName = "userList"; - public static shouldShare = false; - public static requireCredential = false; - private listId: string; - public listUsers: User["id"][] = []; - private listUsersClock: NodeJS.Timer; - - constructor(id: string, connection: Channel["connection"]) { - super(id, connection); - this.updateListUsers = this.updateListUsers.bind(this); - this.onNote = this.withPackedNote(this.onNote.bind(this)); - } - - public async init(params: any) { - this.listId = params.listId as string; - - // Check existence and owner - const list = await UserLists.findOneBy({ - id: this.listId, - userId: this.user!.id, - }); - if (!list) return; - - // Subscribe stream - this.subscriber.on(`userListStream:${this.listId}`, this.send); - - this.subscriber.on("notesStream", this.onNote); - - this.updateListUsers(); - this.listUsersClock = setInterval(this.updateListUsers, 5000); - } - - private async updateListUsers() { - const users = await UserListJoinings.find({ - where: { - userListId: this.listId, - }, - select: ["userId"], - }); - - this.listUsers = users.map((x) => x.userId); - } - - private async onNote(note: Packed<"Note">) { - if (!this.listUsers.includes(note.userId)) return; - - // 流れてきたNoteがミュートしているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.muting)) return; - // 流れてきたNoteがブロックされているユーザーが関わるものだったら無視する - if (isUserRelated(note, this.blocking)) return; - - if (note.renote && !note.text && isUserRelated(note, this.renoteMuting)) - return; - - this.send("note", note); - } - - public dispose() { - // Unsubscribe events - this.subscriber.off(`userListStream:${this.listId}`, this.send); - this.subscriber.off("notesStream", this.onNote); - - clearInterval(this.listUsersClock); - } -} diff --git a/packages/backend/src/server/api/stream/index.ts b/packages/backend/src/server/api/stream/index.ts deleted file mode 100644 index 055fe200b7..0000000000 --- a/packages/backend/src/server/api/stream/index.ts +++ /dev/null @@ -1,621 +0,0 @@ -import type { EventEmitter } from "events"; -import type * as websocket from "websocket"; -import readNote from "@/services/note/read.js"; -import type { User } from "@/models/entities/user.js"; -import type { Channel as ChannelModel } from "@/models/entities/channel.js"; -import { - Users, - Followings, - Mutings, - RenoteMutings, - UserProfiles, - ChannelFollowings, - Blockings, -} from "@/models/index.js"; -import type { AccessToken } from "@/models/entities/access-token.js"; -import type { UserProfile } from "@/models/entities/user-profile.js"; -import { - publishChannelStream, - publishGroupMessagingStream, - publishMessagingStream, -} from "@/services/stream.js"; -import type { UserGroup } from "@/models/entities/user-group.js"; -import type { Packed } from "@/misc/schema.js"; -import { readNotification } from "../common/read-notification.js"; -import channels from "./channels/index.js"; -import type Channel from "./channel.js"; -import type { StreamEventEmitter, StreamMessages } from "./types.js"; -import { Converter } from "@calckey/megalodon"; -import { getClient } from "../mastodon/ApiMastodonCompatibleService.js"; -import { toTextWithReaction } from "../mastodon/endpoints/timeline.js"; - -/** - * Main stream connection - */ -export default class Connection { - public user?: User; - public userProfile?: UserProfile | null; - public following: Set<User["id"]> = new Set(); - public muting: Set<User["id"]> = new Set(); - public renoteMuting: Set<User["id"]> = new Set(); - public blocking: Set<User["id"]> = new Set(); // "被"blocking - public followingChannels: Set<ChannelModel["id"]> = new Set(); - public token?: AccessToken; - private wsConnection: websocket.connection; - public subscriber: StreamEventEmitter; - private channels: Channel[] = []; - private subscribingNotes: Map<string, number> = new Map(); - private cachedNotes: Packed<"Note">[] = []; - private isMastodonCompatible: boolean = false; - private host: string; - private accessToken: string; - private currentSubscribe: string[][] = []; - - constructor( - wsConnection: websocket.connection, - subscriber: EventEmitter, - user: User | null | undefined, - token: AccessToken | null | undefined, - host: string, - accessToken: string, - prepareStream: string | undefined, - ) { - console.log("constructor", prepareStream); - this.wsConnection = wsConnection; - this.subscriber = subscriber; - if (user) this.user = user; - if (token) this.token = token; - if (host) this.host = host; - if (accessToken) this.accessToken = accessToken; - - this.onWsConnectionMessage = this.onWsConnectionMessage.bind(this); - this.onUserEvent = this.onUserEvent.bind(this); - this.onNoteStreamMessage = this.onNoteStreamMessage.bind(this); - this.onBroadcastMessage = this.onBroadcastMessage.bind(this); - - this.wsConnection.on("message", this.onWsConnectionMessage); - - this.subscriber.on("broadcast", (data) => { - this.onBroadcastMessage(data); - }); - - if (this.user) { - this.updateFollowing(); - this.updateMuting(); - this.updateRenoteMuting(); - this.updateBlocking(); - this.updateFollowingChannels(); - this.updateUserProfile(); - - this.subscriber.on(`user:${this.user.id}`, this.onUserEvent); - } - console.log("prepare", prepareStream); - if (prepareStream) { - this.onWsConnectionMessage({ - type: "utf8", - utf8Data: JSON.stringify({ stream: prepareStream, type: "subscribe" }), - }); - } - } - - private onUserEvent(data: StreamMessages["user"]["payload"]) { - // { type, body }と展開するとそれぞれ型が分離してしまう - switch (data.type) { - case "follow": - this.following.add(data.body.id); - break; - - case "unfollow": - this.following.delete(data.body.id); - break; - - case "mute": - this.muting.add(data.body.id); - break; - - case "unmute": - this.muting.delete(data.body.id); - break; - - // TODO: renote mute events - // TODO: block events - - case "followChannel": - this.followingChannels.add(data.body.id); - break; - - case "unfollowChannel": - this.followingChannels.delete(data.body.id); - break; - - case "updateUserProfile": - this.userProfile = data.body; - break; - - case "terminate": - this.wsConnection.close(); - this.dispose(); - break; - - default: - break; - } - } - - /** - * クライアントからメッセージ受信時 - */ - private async onWsConnectionMessage(data: websocket.Message) { - if (data.type !== "utf8") return; - if (data.utf8Data == null) return; - - let objs: Record<string, any>[]; - - try { - objs = [JSON.parse(data.utf8Data)]; - } catch (e) { - return; - } - - const simpleObj = objs[0]; - if (simpleObj.stream) { - // is Mastodon Compatible - this.isMastodonCompatible = true; - if (simpleObj.type === "subscribe") { - let forSubscribe = []; - if (simpleObj.stream === "user") { - this.currentSubscribe.push(["user"]); - objs = [ - { - type: "connect", - body: { - channel: "main", - id: simpleObj.stream, - }, - }, - { - type: "connect", - body: { - channel: "homeTimeline", - id: simpleObj.stream, - }, - }, - ]; - const client = getClient(this.host, this.accessToken); - try { - const tl = await client.getHomeTimeline(); - for (const t of tl.data) forSubscribe.push(t.id); - } catch (e: any) { - console.log(e); - console.error(e.response.data); - } - } else if (simpleObj.stream === "public:local") { - this.currentSubscribe.push(["public:local"]); - objs = [ - { - type: "connect", - body: { - channel: "localTimeline", - id: simpleObj.stream, - }, - }, - ]; - const client = getClient(this.host, this.accessToken); - const tl = await client.getLocalTimeline(); - for (const t of tl.data) forSubscribe.push(t.id); - } else if (simpleObj.stream === "public") { - this.currentSubscribe.push(["public"]); - objs = [ - { - type: "connect", - body: { - channel: "globalTimeline", - id: simpleObj.stream, - }, - }, - ]; - const client = getClient(this.host, this.accessToken); - const tl = await client.getPublicTimeline(); - for (const t of tl.data) forSubscribe.push(t.id); - } else if (simpleObj.stream === "list") { - this.currentSubscribe.push(["list", simpleObj.list]); - objs = [ - { - type: "connect", - body: { - channel: "list", - id: simpleObj.stream, - params: { - listId: simpleObj.list, - }, - }, - }, - ]; - const client = getClient(this.host, this.accessToken); - const tl = await client.getListTimeline(simpleObj.list); - for (const t of tl.data) forSubscribe.push(t.id); - } - for (const s of forSubscribe) { - objs.push({ - type: "s", - body: { - id: s, - }, - }); - } - } - } - - for (const obj of objs) { - const { type, body } = obj; - console.log(type, body); - switch (type) { - case "readNotification": - this.onReadNotification(body); - break; - case "subNote": - this.onSubscribeNote(body); - break; - case "s": - this.onSubscribeNote(body); - break; // alias - case "sr": - this.onSubscribeNote(body); - this.readNote(body); - break; - case "unsubNote": - this.onUnsubscribeNote(body); - break; - case "un": - this.onUnsubscribeNote(body); - break; // alias - case "connect": - this.onChannelConnectRequested(body); - break; - case "disconnect": - this.onChannelDisconnectRequested(body); - break; - case "channel": - this.onChannelMessageRequested(body); - break; - case "ch": - this.onChannelMessageRequested(body); - break; // alias - - // 個々のチャンネルではなくルートレベルでこれらのメッセージを受け取る理由は、 - // クライアントの事情を考慮したとき、入力フォームはノートチャンネルやメッセージのメインコンポーネントとは別 - // なこともあるため、それらのコンポーネントがそれぞれ各チャンネルに接続するようにするのは面倒なため。 - case "typingOnChannel": - this.typingOnChannel(body.channel); - break; - case "typingOnMessaging": - this.typingOnMessaging(body); - break; - } - } - } - - private onBroadcastMessage(data: StreamMessages["broadcast"]["payload"]) { - this.sendMessageToWs(data.type, data.body); - } - - public cacheNote(note: Packed<"Note">) { - const add = (note: Packed<"Note">) => { - const existIndex = this.cachedNotes.findIndex((n) => n.id === note.id); - if (existIndex > -1) { - this.cachedNotes[existIndex] = note; - return; - } - - this.cachedNotes.unshift(note); - if (this.cachedNotes.length > 32) { - this.cachedNotes.splice(32); - } - }; - - add(note); - if (note.reply) add(note.reply); - if (note.renote) add(note.renote); - } - - private readNote(body: any) { - const id = body.id; - - const note = this.cachedNotes.find((n) => n.id === id); - if (note == null) return; - - if (this.user && note.userId !== this.user.id) { - readNote(this.user.id, [note], { - following: this.following, - followingChannels: this.followingChannels, - }); - } - } - - private onReadNotification(payload: any) { - if (!payload.id) return; - readNotification(this.user!.id, [payload.id]); - } - - /** - * 投稿購読要求時 - */ - private onSubscribeNote(payload: any) { - if (!payload.id) return; - - const current = this.subscribingNotes.get(payload.id) || 0; - this.subscribingNotes.set(payload.id, current + 1); - - if (!current) { - this.subscriber.on(`noteStream:${payload.id}`, this.onNoteStreamMessage); - } - } - - /** - * 投稿購読解除要求時 - */ - private onUnsubscribeNote(payload: any) { - if (!payload.id) return; - - const current = this.subscribingNotes.get(payload.id) || 0; - if (current <= 1) { - this.subscribingNotes.delete(payload.id); - this.subscriber.off(`noteStream:${payload.id}`, this.onNoteStreamMessage); - return; - } - this.subscribingNotes.set(payload.id, current - 1); - } - - private async onNoteStreamMessage(data: StreamMessages["note"]["payload"]) { - this.sendMessageToWs("noteUpdated", { - id: data.body.id, - type: data.type, - body: data.body.body, - }); - } - - /** - * チャンネル接続要求時 - */ - private onChannelConnectRequested(payload: any) { - const { channel, id, params, pong } = payload; - this.connectChannel(id, params, channel, pong); - } - - /** - * チャンネル切断要求時 - */ - private onChannelDisconnectRequested(payload: any) { - const { id } = payload; - this.disconnectChannel(id); - } - - /** - * クライアントにメッセージ送信 - */ - public sendMessageToWs(type: string, payload: any) { - console.log(payload, this.isMastodonCompatible); - if (this.isMastodonCompatible) { - if (payload.type === "note") { - this.wsConnection.send( - JSON.stringify({ - stream: [payload.id], - event: "update", - payload: JSON.stringify( - toTextWithReaction( - [Converter.note(payload.body, this.host)], - this.host, - )[0], - ), - }), - ); - this.onSubscribeNote({ - id: payload.body.id, - }); - } else if (payload.type === "reacted" || payload.type === "unreacted") { - // reaction - const client = getClient(this.host, this.accessToken); - client.getStatus(payload.id).then((data) => { - const newPost = toTextWithReaction([data.data], this.host); - const targetPost = newPost[0]; - for (const stream of this.currentSubscribe) { - this.wsConnection.send( - JSON.stringify({ - stream, - event: "status.update", - payload: JSON.stringify(targetPost), - }), - ); - } - }); - } else if (payload.type === "deleted") { - // delete - for (const stream of this.currentSubscribe) { - this.wsConnection.send( - JSON.stringify({ - stream, - event: "delete", - payload: payload.id, - }), - ); - } - } else if (payload.type === "unreadNotification") { - if (payload.id === "user") { - const body = Converter.notification(payload.body, this.host); - if (body.type === "reaction") body.type = "favourite"; - body.status = toTextWithReaction( - body.status ? [body.status] : [], - "", - )[0]; - this.wsConnection.send( - JSON.stringify({ - stream: ["user"], - event: "notification", - payload: JSON.stringify(body), - }), - ); - } - } - } else { - this.wsConnection.send( - JSON.stringify({ - type: type, - body: payload, - }), - ); - } - } - - /** - * チャンネルに接続 - */ - public connectChannel( - id: string, - params: any, - channel: string, - pong = false, - ) { - if ((channels as any)[channel].requireCredential && this.user == null) { - return; - } - - // 共有可能チャンネルに接続しようとしていて、かつそのチャンネルに既に接続していたら無意味なので無視 - if ( - (channels as any)[channel].shouldShare && - this.channels.some((c) => c.chName === channel) - ) { - return; - } - - const ch: Channel = new (channels as any)[channel](id, this); - this.channels.push(ch); - ch.init(params); - - if (pong) { - this.sendMessageToWs("connected", { - id: id, - }); - } - } - - /** - * チャンネルから切断 - * @param id チャンネルコネクションID - */ - public disconnectChannel(id: string) { - const channel = this.channels.find((c) => c.id === id); - - if (channel) { - if (channel.dispose) channel.dispose(); - this.channels = this.channels.filter((c) => c.id !== id); - } - } - - /** - * チャンネルへメッセージ送信要求時 - * @param data メッセージ - */ - private onChannelMessageRequested(data: any) { - const channel = this.channels.find((c) => c.id === data.id); - if (channel?.onMessage != null) { - channel.onMessage(data.type, data.body); - } - } - - private typingOnChannel(channel: ChannelModel["id"]) { - if (this.user) { - publishChannelStream(channel, "typing", this.user.id); - } - } - - private typingOnMessaging(param: { - partner?: User["id"]; - group?: UserGroup["id"]; - }) { - if (this.user) { - if (param.partner) { - publishMessagingStream( - param.partner, - this.user.id, - "typing", - this.user.id, - ); - } else if (param.group) { - publishGroupMessagingStream(param.group, "typing", this.user.id); - } - } - } - - private async updateFollowing() { - const followings = await Followings.find({ - where: { - followerId: this.user!.id, - }, - select: ["followeeId"], - }); - - this.following = new Set<string>(followings.map((x) => x.followeeId)); - } - - private async updateMuting() { - const mutings = await Mutings.find({ - where: { - muterId: this.user!.id, - }, - select: ["muteeId"], - }); - - this.muting = new Set<string>(mutings.map((x) => x.muteeId)); - } - - private async updateRenoteMuting() { - const renoteMutings = await RenoteMutings.find({ - where: { - muterId: this.user!.id, - }, - select: ["muteeId"], - }); - - this.renoteMuting = new Set<string>(renoteMutings.map((x) => x.muteeId)); - } - - private async updateBlocking() { - // ここでいうBlockingは被Blockingの意 - const blockings = await Blockings.find({ - where: { - blockeeId: this.user!.id, - }, - select: ["blockerId"], - }); - - this.blocking = new Set<string>(blockings.map((x) => x.blockerId)); - } - - private async updateFollowingChannels() { - const followings = await ChannelFollowings.find({ - where: { - followerId: this.user!.id, - }, - select: ["followeeId"], - }); - - this.followingChannels = new Set<string>( - followings.map((x) => x.followeeId), - ); - } - - private async updateUserProfile() { - this.userProfile = await UserProfiles.findOneBy({ - userId: this.user!.id, - }); - } - - /** - * ストリームが切れたとき - */ - public dispose() { - for (const c of this.channels.filter((c) => c.dispose)) { - if (c.dispose) c.dispose(); - } - } -} diff --git a/packages/backend/src/server/api/stream/types.ts b/packages/backend/src/server/api/stream/types.ts deleted file mode 100644 index 9becf9f642..0000000000 --- a/packages/backend/src/server/api/stream/types.ts +++ /dev/null @@ -1,292 +0,0 @@ -import type { EventEmitter } from "events"; -import type Emitter from "strict-event-emitter-types"; -import type { Channel } from "@/models/entities/channel.js"; -import type { User } from "@/models/entities/user.js"; -import type { UserProfile } from "@/models/entities/user-profile.js"; -import type { Note } from "@/models/entities/note.js"; -import type { Antenna } from "@/models/entities/antenna.js"; -import type { DriveFile } from "@/models/entities/drive-file.js"; -import type { DriveFolder } from "@/models/entities/drive-folder.js"; -import type { UserList } from "@/models/entities/user-list.js"; -import type { MessagingMessage } from "@/models/entities/messaging-message.js"; -import type { UserGroup } from "@/models/entities/user-group.js"; -import type { AbuseUserReport } from "@/models/entities/abuse-user-report.js"; -import type { Signin } from "@/models/entities/signin.js"; -import type { Page } from "@/models/entities/page.js"; -import type { Packed } from "@/misc/schema.js"; -import type { Webhook } from "@/models/entities/webhook"; - -//#region Stream type-body definitions -export interface InternalStreamTypes { - userChangeSuspendedState: { - id: User["id"]; - isSuspended: User["isSuspended"]; - }; - userChangeSilencedState: { - id: User["id"]; - isSilenced: User["isSilenced"]; - }; - userChangeModeratorState: { - id: User["id"]; - isModerator: User["isModerator"]; - }; - userTokenRegenerated: { - id: User["id"]; - oldToken: User["token"]; - newToken: User["token"]; - }; - localUserUpdated: { - id: User["id"]; - }; - remoteUserUpdated: { - id: User["id"]; - }; - webhookCreated: Webhook; - webhookDeleted: Webhook; - webhookUpdated: Webhook; - antennaCreated: Antenna; - antennaDeleted: Antenna; - antennaUpdated: Antenna; -} - -export interface BroadcastTypes { - emojiAdded: { - emoji: Packed<"Emoji">; - }; -} - -export interface UserStreamTypes { - terminate: Record<string, unknown>; - followChannel: Channel; - unfollowChannel: Channel; - updateUserProfile: UserProfile; - mute: User; - unmute: User; - follow: Packed<"UserDetailedNotMe">; - unfollow: Packed<"User">; - userAdded: Packed<"User">; -} - -export interface MainStreamTypes { - notification: Packed<"Notification">; - mention: Packed<"Note">; - reply: Packed<"Note">; - renote: Packed<"Note">; - follow: Packed<"UserDetailedNotMe">; - followed: Packed<"User">; - unfollow: Packed<"User">; - meUpdated: Packed<"User">; - pageEvent: { - pageId: Page["id"]; - event: string; - var: any; - userId: User["id"]; - user: Packed<"User">; - }; - urlUploadFinished: { - marker?: string | null; - file: Packed<"DriveFile">; - }; - readAllNotifications: undefined; - unreadNotification: Packed<"Notification">; - unreadMention: Note["id"]; - readAllUnreadMentions: undefined; - unreadSpecifiedNote: Note["id"]; - readAllUnreadSpecifiedNotes: undefined; - readAllMessagingMessages: undefined; - messagingMessage: Packed<"MessagingMessage">; - unreadMessagingMessage: Packed<"MessagingMessage">; - readAllAntennas: undefined; - unreadAntenna: Antenna; - readAllAnnouncements: undefined; - readAllChannels: undefined; - unreadChannel: Note["id"]; - myTokenRegenerated: undefined; - signin: Signin; - registryUpdated: { - scope?: string[]; - key: string; - value: any | null; - }; - driveFileCreated: Packed<"DriveFile">; - readAntenna: Antenna; - receiveFollowRequest: Packed<"User">; -} - -export interface DriveStreamTypes { - fileCreated: Packed<"DriveFile">; - fileDeleted: DriveFile["id"]; - fileUpdated: Packed<"DriveFile">; - folderCreated: Packed<"DriveFolder">; - folderDeleted: DriveFolder["id"]; - folderUpdated: Packed<"DriveFolder">; -} - -export interface NoteStreamTypes { - pollVoted: { - choice: number; - userId: User["id"]; - }; - deleted: { - deletedAt: Date; - }; - reacted: { - reaction: string; - emoji?: { - name: string; - url: string; - } | null; - userId: User["id"]; - }; - unreacted: { - reaction: string; - userId: User["id"]; - }; - replied: { - id: Note["id"]; - }; -} -type NoteStreamEventTypes = { - [key in keyof NoteStreamTypes]: { - id: Note["id"]; - body: NoteStreamTypes[key]; - }; -}; - -export interface ChannelStreamTypes { - typing: User["id"]; -} - -export interface UserListStreamTypes { - userAdded: Packed<"User">; - userRemoved: Packed<"User">; -} - -export interface AntennaStreamTypes { - note: Note; -} - -export interface MessagingStreamTypes { - read: MessagingMessage["id"][]; - typing: User["id"]; - message: Packed<"MessagingMessage">; - deleted: MessagingMessage["id"]; -} - -export interface GroupMessagingStreamTypes { - read: { - ids: MessagingMessage["id"][]; - userId: User["id"]; - }; - typing: User["id"]; - message: Packed<"MessagingMessage">; - deleted: MessagingMessage["id"]; -} - -export interface MessagingIndexStreamTypes { - read: MessagingMessage["id"][]; - message: Packed<"MessagingMessage">; -} - -export interface AdminStreamTypes { - newAbuseUserReport: { - id: AbuseUserReport["id"]; - targetUserId: User["id"]; - reporterId: User["id"]; - comment: string; - }; -} -//#endregion - -// 辞書(interface or type)から{ type, body }ユニオンを定義 -// https://stackoverflow.com/questions/49311989/can-i-infer-the-type-of-a-value-using-extends-keyof-type -// VS Codeの展開を防止するためにEvents型を定義 -type Events<T extends object> = { [K in keyof T]: { type: K; body: T[K] } }; -type EventUnionFromDictionary<T extends object, U = Events<T>> = U[keyof U]; - -// name/messages(spec) pairs dictionary -export type StreamMessages = { - internal: { - name: "internal"; - payload: EventUnionFromDictionary<InternalStreamTypes>; - }; - broadcast: { - name: "broadcast"; - payload: EventUnionFromDictionary<BroadcastTypes>; - }; - user: { - name: `user:${User["id"]}`; - payload: EventUnionFromDictionary<UserStreamTypes>; - }; - main: { - name: `mainStream:${User["id"]}`; - payload: EventUnionFromDictionary<MainStreamTypes>; - }; - drive: { - name: `driveStream:${User["id"]}`; - payload: EventUnionFromDictionary<DriveStreamTypes>; - }; - note: { - name: `noteStream:${Note["id"]}`; - payload: EventUnionFromDictionary<NoteStreamEventTypes>; - }; - channel: { - name: `channelStream:${Channel["id"]}`; - payload: EventUnionFromDictionary<ChannelStreamTypes>; - }; - userList: { - name: `userListStream:${UserList["id"]}`; - payload: EventUnionFromDictionary<UserListStreamTypes>; - }; - antenna: { - name: `antennaStream:${Antenna["id"]}`; - payload: EventUnionFromDictionary<AntennaStreamTypes>; - }; - messaging: { - name: `messagingStream:${User["id"]}-${User["id"]}`; - payload: EventUnionFromDictionary<MessagingStreamTypes>; - }; - groupMessaging: { - name: `messagingStream:${UserGroup["id"]}`; - payload: EventUnionFromDictionary<GroupMessagingStreamTypes>; - }; - messagingIndex: { - name: `messagingIndexStream:${User["id"]}`; - payload: EventUnionFromDictionary<MessagingIndexStreamTypes>; - }; - admin: { - name: `adminStream:${User["id"]}`; - payload: EventUnionFromDictionary<AdminStreamTypes>; - }; - notes: { - name: "notesStream"; - payload: Note; - }; -}; - -// API event definitions -// ストリームごとのEmitterの辞書を用意 -type EventEmitterDictionary = { - [x in keyof StreamMessages]: Emitter< - EventEmitter, - { - [y in StreamMessages[x]["name"]]: ( - e: StreamMessages[x]["payload"], - ) => void; - } - >; -}; -// 共用体型を交差型にする型 https://stackoverflow.com/questions/54938141/typescript-convert-union-to-intersection -type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ( - k: infer I, -) => void - ? I - : never; -// Emitter辞書から共用体型を作り、UnionToIntersectionで交差型にする -export type StreamEventEmitter = UnionToIntersection< - EventEmitterDictionary[keyof StreamMessages] ->; -// { [y in name]: (e: spec) => void }をまとめてその交差型をEmitterにかけるとts(2590)にひっかかる - -// provide stream channels union -export type StreamChannels = StreamMessages[keyof StreamMessages]["name"]; diff --git a/packages/backend/src/server/api/streaming.ts b/packages/backend/src/server/api/streaming.ts deleted file mode 100644 index 14e07b7487..0000000000 --- a/packages/backend/src/server/api/streaming.ts +++ /dev/null @@ -1,89 +0,0 @@ -import type * as http from "node:http"; -import { EventEmitter } from "events"; -import type { ParsedUrlQuery } from "querystring"; -import * as websocket from "websocket"; - -import { subscriber as redisClient } from "@/db/redis.js"; -import { Users } from "@/models/index.js"; -import MainStreamConnection from "./stream/index.js"; -import authenticate from "./authenticate.js"; - -export const initializeStreamingServer = (server: http.Server) => { - // Init websocket server - const ws = new websocket.server({ - httpServer: server, - }); - - ws.on("request", async (request) => { - const q = request.resourceURL.query as ParsedUrlQuery; - const headers = request.httpRequest.headers["sec-websocket-protocol"] || ""; - const cred = q.i || q.access_token || headers; - const accessToken = cred.toString(); - - const [user, app] = await authenticate( - request.httpRequest.headers.authorization, - accessToken, - ).catch((err) => { - request.reject(403, err.message); - return []; - }); - if (typeof user === "undefined") { - return; - } - - if (user?.isSuspended) { - request.reject(400); - return; - } - - const connection = request.accept(); - - const ev = new EventEmitter(); - - async function onRedisMessage(_: string, data: string) { - const parsed = JSON.parse(data); - ev.emit(parsed.channel, parsed.message); - } - - redisClient.on("message", onRedisMessage); - const host = `https://${request.host}`; - const prepareStream = q.stream?.toString(); - console.log("start", q); - - const main = new MainStreamConnection( - connection, - ev, - user, - app, - host, - accessToken, - prepareStream, - ); - - const intervalId = user - ? setInterval(() => { - Users.update(user.id, { - lastActiveDate: new Date(), - }); - }, 1000 * 60 * 5) - : null; - if (user) { - Users.update(user.id, { - lastActiveDate: new Date(), - }); - } - - connection.once("close", () => { - ev.removeAllListeners(); - main.dispose(); - redisClient.off("message", onRedisMessage); - if (intervalId) clearInterval(intervalId); - }); - - connection.on("message", async (data) => { - if (data.type === "utf8" && data.utf8Data === "ping") { - connection.send("pong"); - } - }); - }); -}; diff --git a/packages/backend/src/server/file/assets/bad-egg.png b/packages/backend/src/server/file/assets/bad-egg.png deleted file mode 100644 index e96ba0dcc1..0000000000 Binary files a/packages/backend/src/server/file/assets/bad-egg.png and /dev/null differ diff --git a/packages/backend/src/server/file/assets/cache-expired.png b/packages/backend/src/server/file/assets/cache-expired.png deleted file mode 100644 index 5d988c502b..0000000000 Binary files a/packages/backend/src/server/file/assets/cache-expired.png and /dev/null differ diff --git a/packages/backend/src/server/file/assets/dummy.png b/packages/backend/src/server/file/assets/dummy.png deleted file mode 100644 index 39332b0c1b..0000000000 Binary files a/packages/backend/src/server/file/assets/dummy.png and /dev/null differ diff --git a/packages/backend/src/server/file/assets/not-an-image.png b/packages/backend/src/server/file/assets/not-an-image.png deleted file mode 100644 index 39e4aa0892..0000000000 Binary files a/packages/backend/src/server/file/assets/not-an-image.png and /dev/null differ diff --git a/packages/backend/src/server/file/assets/thumbnail-not-available.png b/packages/backend/src/server/file/assets/thumbnail-not-available.png deleted file mode 100644 index 07cad9919c..0000000000 Binary files a/packages/backend/src/server/file/assets/thumbnail-not-available.png and /dev/null differ diff --git a/packages/backend/src/server/file/assets/tombstone.png b/packages/backend/src/server/file/assets/tombstone.png deleted file mode 100644 index 83159d6b3c..0000000000 Binary files a/packages/backend/src/server/file/assets/tombstone.png and /dev/null differ diff --git a/packages/backend/src/server/file/index.ts b/packages/backend/src/server/file/index.ts deleted file mode 100644 index 26df1de51d..0000000000 --- a/packages/backend/src/server/file/index.ts +++ /dev/null @@ -1,43 +0,0 @@ -/** - * File Server - */ - -import * as fs from "node:fs"; -import { fileURLToPath } from "node:url"; -import { dirname } from "node:path"; -import Koa from "koa"; -import cors from "@koa/cors"; -import Router from "@koa/router"; -import sendDriveFile from "./send-drive-file.js"; - -const _filename = fileURLToPath(import.meta.url); -const _dirname = dirname(_filename); - -// Init app -const app = new Koa(); -app.use(cors()); -app.use(async (ctx, next) => { - ctx.set( - "Content-Security-Policy", - `default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'`, - ); - await next(); -}); - -// Init router -const router = new Router(); - -router.get("/app-default.jpg", (ctx) => { - const file = fs.createReadStream(`${_dirname}/assets/dummy.png`); - ctx.body = file; - ctx.set("Content-Type", "image/jpeg"); - ctx.set("Cache-Control", "max-age=31536000, immutable"); -}); - -router.get("/:key", sendDriveFile); -router.get("/:key/(.*)", sendDriveFile); - -// Register router -app.use(router.routes()); - -export default app; diff --git a/packages/backend/src/server/file/send-drive-file.ts b/packages/backend/src/server/file/send-drive-file.ts deleted file mode 100644 index 0877369025..0000000000 --- a/packages/backend/src/server/file/send-drive-file.ts +++ /dev/null @@ -1,152 +0,0 @@ -import * as fs from "node:fs"; -import { fileURLToPath } from "node:url"; -import { dirname } from "node:path"; -import type Koa from "koa"; -import send from "koa-send"; -import rename from "rename"; -import { serverLogger } from "../index.js"; -import { contentDisposition } from "@/misc/content-disposition.js"; -import { DriveFiles } from "@/models/index.js"; -import { InternalStorage } from "@/services/drive/internal-storage.js"; -import { createTemp } from "@/misc/create-temp.js"; -import { downloadUrl } from "@/misc/download-url.js"; -import { detectType } from "@/misc/get-file-info.js"; -import { convertToWebp } from "@/services/drive/image-processor.js"; -import { GenerateVideoThumbnail } from "@/services/drive/generate-video-thumbnail.js"; -import { StatusError } from "@/misc/fetch.js"; -import { FILE_TYPE_BROWSERSAFE } from "@/const.js"; - -const _filename = fileURLToPath(import.meta.url); -const _dirname = dirname(_filename); - -const assets = `${_dirname}/../../server/file/assets/`; - -const commonReadableHandlerGenerator = - (ctx: Koa.Context) => (e: Error): void => { - serverLogger.error(e); - ctx.status = 500; - ctx.set("Cache-Control", "max-age=300"); - }; - -export default async function (ctx: Koa.Context) { - const key = ctx.params.key; - - // Fetch drive file - const file = await DriveFiles.createQueryBuilder("file") - .where("file.accessKey = :accessKey", { accessKey: key }) - .orWhere("file.thumbnailAccessKey = :thumbnailAccessKey", { - thumbnailAccessKey: key, - }) - .orWhere("file.webpublicAccessKey = :webpublicAccessKey", { - webpublicAccessKey: key, - }) - .getOne(); - - if (file == null) { - ctx.status = 404; - ctx.set("Cache-Control", "max-age=86400"); - await send(ctx as any, "/dummy.png", { root: assets }); - return; - } - - const isThumbnail = file.thumbnailAccessKey === key; - const isWebpublic = file.webpublicAccessKey === key; - - if (!file.storedInternal) { - if (file.isLink && file.uri) { - // 期限切れリモートファイル - const [path, cleanup] = await createTemp(); - - try { - await downloadUrl(file.uri, path); - - const { mime, ext } = await detectType(path); - - const convertFile = async () => { - if (isThumbnail) { - if ( - [ - "image/jpeg", - "image/webp", - "image/png", - "image/svg+xml", - "image/avif", - ].includes(mime) - ) { - return await convertToWebp(path, 996, 560); - } else if (mime.startsWith("video/")) { - return await GenerateVideoThumbnail(path); - } - } - - if (isWebpublic) { - if (["image/svg+xml"].includes(mime)) { - return await convertToWebp(path, 2048, 2048, 100); - } - } - - return { - data: fs.readFileSync(path), - ext, - type: mime, - }; - }; - - const image = await convertFile(); - ctx.body = image.data; - ctx.set( - "Content-Type", - FILE_TYPE_BROWSERSAFE.includes(image.type) - ? image.type - : "application/octet-stream", - ); - ctx.set("Cache-Control", "max-age=31536000, immutable"); - } catch (e) { - serverLogger.error(`${e}`); - - if (e instanceof StatusError && e.isClientError) { - ctx.status = e.statusCode; - ctx.set("Cache-Control", "max-age=86400"); - } else { - ctx.status = 500; - ctx.set("Cache-Control", "max-age=300"); - } - } finally { - cleanup(); - } - return; - } - - ctx.status = 204; - ctx.set("Cache-Control", "max-age=86400"); - return; - } - - if (isThumbnail || isWebpublic) { - const { mime, ext } = await detectType(InternalStorage.resolvePath(key)); - const filename = rename(file.name, { - suffix: isThumbnail ? "-thumb" : "-web", - extname: ext ? `.${ext}` : undefined, - }).toString(); - - ctx.body = InternalStorage.read(key); - ctx.set( - "Content-Type", - FILE_TYPE_BROWSERSAFE.includes(mime) ? mime : "application/octet-stream", - ); - ctx.set("Cache-Control", "max-age=31536000, immutable"); - ctx.set("Content-Disposition", contentDisposition("inline", filename)); - } else { - const readable = InternalStorage.read(file.accessKey!); - readable.on("error", commonReadableHandlerGenerator(ctx)); - ctx.body = readable; - ctx.set( - "Content-Type", - FILE_TYPE_BROWSERSAFE.includes(file.type) - ? file.type - : "application/octet-stream", - ); - ctx.set("Cache-Control", "max-age=31536000, immutable"); - ctx.set("Content-Disposition", contentDisposition("inline", file.name)); - } -} diff --git a/packages/backend/src/server/index.ts b/packages/backend/src/server/index.ts deleted file mode 100644 index 7d274f7d28..0000000000 --- a/packages/backend/src/server/index.ts +++ /dev/null @@ -1,286 +0,0 @@ -/** - * Core Server - */ - -import cluster from "node:cluster"; -import * as fs from "node:fs"; -import * as http from "node:http"; -import Koa from "koa"; -import Router from "@koa/router"; -import mount from "koa-mount"; -import koaLogger from "koa-logger"; -import * as slow from "koa-slow"; -import { IsNull } from "typeorm"; -import config from "@/config/index.js"; -import Logger from "@/services/logger.js"; -import { UserProfiles, Users } from "@/models/index.js"; -import { genIdenticon } from "@/misc/gen-identicon.js"; -import { createTemp } from "@/misc/create-temp.js"; -import { publishMainStream } from "@/services/stream.js"; -import * as Acct from "@/misc/acct.js"; -import { envOption } from "@/env.js"; -import megalodon, { MegalodonInterface } from "@calckey/megalodon"; -import activityPub from "./activitypub.js"; -import nodeinfo from "./nodeinfo.js"; -import wellKnown from "./well-known.js"; -import apiServer from "./api/index.js"; -import fileServer from "./file/index.js"; -import proxyServer from "./proxy/index.js"; -import webServer from "./web/index.js"; -import { initializeStreamingServer } from "./api/streaming.js"; -import { koaBody } from "koa-body"; -import { v4 as uuid } from "uuid"; - -export const serverLogger = new Logger("server", "gray", false); - -// Init app -const app = new Koa(); -app.proxy = true; - -// Replace trailing slashes -app.use(async (ctx, next) => { - if (ctx.request.path !== "/" && ctx.request.path.endsWith("/")) - return ctx.redirect(ctx.request.path.replace(/\/$/, "")); - else await next(); -}); - -if (!["production", "test"].includes(process.env.NODE_ENV || "")) { - // Logger - app.use( - koaLogger((str) => { - serverLogger.info(str); - }), - ); - - // Delay - if (envOption.slow) { - app.use( - slow({ - delay: 3000, - }), - ); - } -} - -// HSTS -// 6months (15552000sec) -if (config.url.startsWith("https") && !config.disableHsts) { - app.use(async (ctx, next) => { - ctx.set("strict-transport-security", "max-age=15552000; preload"); - await next(); - }); -} - -app.use(mount("/api", apiServer)); -app.use(mount("/files", fileServer)); -app.use(mount("/proxy", proxyServer)); - -// Init router -const router = new Router(); -const mastoRouter = new Router(); - -mastoRouter.use( - koaBody({ - urlencoded: true, - multipart: true, - }), -); - -mastoRouter.use(async (ctx, next) => { - if (ctx.request.query) { - if (!ctx.request.body || Object.keys(ctx.request.body).length === 0) { - ctx.request.body = ctx.request.query; - } else { - ctx.request.body = { ...ctx.request.body, ...ctx.request.query }; - } - } - await next(); -}); - -// Routing -router.use(activityPub.routes()); -router.use(nodeinfo.routes()); -router.use(wellKnown.routes()); - -router.get("/avatar/@:acct", async (ctx) => { - const { username, host } = Acct.parse(ctx.params.acct); - const user = await Users.findOne({ - where: { - usernameLower: username.toLowerCase(), - host: host == null || host === config.host ? IsNull() : host, - isSuspended: false, - }, - relations: ["avatar"], - }); - - if (user) { - ctx.redirect(Users.getAvatarUrlSync(user)); - } else { - ctx.redirect("/static-assets/user-unknown.png"); - } -}); - -router.get("/identicon/:x", async (ctx) => { - const [temp, cleanup] = await createTemp(); - await genIdenticon(ctx.params.x, fs.createWriteStream(temp)); - ctx.set("Content-Type", "image/png"); - ctx.body = fs.createReadStream(temp).on("close", () => cleanup()); -}); - -router.get("/verify-email/:code", async (ctx) => { - const profile = await UserProfiles.findOneBy({ - emailVerifyCode: ctx.params.code, - }); - - if (profile != null) { - ctx.body = "Verify succeeded!"; - ctx.status = 200; - - await UserProfiles.update( - { userId: profile.userId }, - { - emailVerified: true, - emailVerifyCode: null, - }, - ); - - publishMainStream( - profile.userId, - "meUpdated", - await Users.pack( - profile.userId, - { id: profile.userId }, - { - detail: true, - includeSecrets: true, - }, - ), - ); - } else { - ctx.status = 404; - } -}); - -mastoRouter.get("/oauth/authorize", async (ctx) => { - const { client_id, state, redirect_uri } = ctx.request.query; - console.log(ctx.request.req); - let param = "mastodon=true"; - if (state) param += `&state=${state}`; - if (redirect_uri) param += `&redirect_uri=${redirect_uri}`; - const client = client_id ? client_id : ""; - ctx.redirect( - `${Buffer.from(client.toString(), "base64").toString()}?${param}`, - ); -}); - -mastoRouter.post("/oauth/token", async (ctx) => { - const body: any = ctx.request.body || ctx.request.query; - console.log("token-request", body); - console.log("token-query", ctx.request.query); - if (body.grant_type === "client_credentials") { - const ret = { - access_token: uuid(), - token_type: "Bearer", - scope: "read", - created_at: Math.floor(new Date().getTime() / 1000), - }; - ctx.body = ret; - return; - } - let client_id: any = body.client_id; - const BASE_URL = `${ctx.request.protocol}://${ctx.request.hostname}`; - const generator = (megalodon as any).default; - const client = generator("misskey", BASE_URL, null) as MegalodonInterface; - let m = null; - let token = null; - if (body.code) { - //m = body.code.match(/^([a-zA-Z0-9]{8})([a-zA-Z0-9]{4})([a-zA-Z0-9]{4})([a-zA-Z0-9]{4})([a-zA-Z0-9]{12})/); - //if (!m.length) { - // ctx.body = { error: "Invalid code" }; - // return; - //} - //token = `${m[1]}-${m[2]}-${m[3]}-${m[4]}-${m[5]}` - console.log(body.code, token); - token = body.code; - } - if (client_id instanceof Array) { - client_id = client_id.toString(); - } else if (!client_id) { - client_id = null; - } - try { - const atData = await client.fetchAccessToken( - client_id, - body.client_secret, - token ? token : "", - ); - const ret = { - access_token: atData.accessToken, - token_type: "Bearer", - scope: body.scope || "read write follow push", - created_at: Math.floor(new Date().getTime() / 1000), - }; - console.log("token-response", ret); - ctx.body = ret; - } catch (err: any) { - console.error(err); - ctx.status = 401; - ctx.body = err.response.data; - } -}); - -// Register router -app.use(mastoRouter.routes()); -app.use(router.routes()); - -app.use(mount(webServer)); - -function createServer() { - return http.createServer(app.callback()); -} - -// For testing -export const startServer = () => { - const server = createServer(); - - initializeStreamingServer(server); - - server.listen(config.port); - - return server; -}; - -export default () => - new Promise((resolve) => { - const server = createServer(); - - initializeStreamingServer(server); - - server.on("error", (e) => { - switch ((e as any).code) { - case "EACCES": - serverLogger.error( - `You do not have permission to listen on port ${config.port}.`, - ); - break; - case "EADDRINUSE": - serverLogger.error( - `Port ${config.port} is already in use by another process.`, - ); - break; - default: - serverLogger.error(e); - break; - } - - if (cluster.isWorker) { - process.send!("listenFailed"); - } else { - // disableClustering - process.exit(1); - } - }); - - // @ts-ignore - server.listen(config.port, resolve); - }); diff --git a/packages/backend/src/server/nodeinfo.ts b/packages/backend/src/server/nodeinfo.ts deleted file mode 100644 index 8563573d47..0000000000 --- a/packages/backend/src/server/nodeinfo.ts +++ /dev/null @@ -1,119 +0,0 @@ -import Router from "@koa/router"; -import config from "@/config/index.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { Users, Notes } from "@/models/index.js"; -import { IsNull, MoreThan } from "typeorm"; -import { MAX_NOTE_TEXT_LENGTH, MAX_CAPTION_TEXT_LENGTH } from "@/const.js"; -import { Cache } from "@/misc/cache.js"; - -const router = new Router(); - -const nodeinfo2_1path = "/nodeinfo/2.1"; -const nodeinfo2_0path = "/nodeinfo/2.0"; - -// to cleo: leave this http or bonks -export const links = [ - { - rel: "http://nodeinfo.diaspora.software/ns/schema/2.1", - href: config.url + nodeinfo2_1path, - }, - { - rel: "http://nodeinfo.diaspora.software/ns/schema/2.0", - href: config.url + nodeinfo2_0path, - }, -]; - -const nodeinfo2 = async () => { - const now = Date.now(); - const [meta, total, activeHalfyear, activeMonth, localPosts] = - await Promise.all([ - fetchMeta(true), - Users.count({ where: { host: IsNull() } }), - Users.count({ - where: { - host: IsNull(), - lastActiveDate: MoreThan(new Date(now - 15552000000)), - }, - }), - Users.count({ - where: { - host: IsNull(), - lastActiveDate: MoreThan(new Date(now - 2592000000)), - }, - }), - Notes.count({ where: { userHost: IsNull() } }), - ]); - - const proxyAccount = meta.proxyAccountId - ? await Users.pack(meta.proxyAccountId).catch(() => null) - : null; - - return { - software: { - name: "calckey", - version: config.version, - repository: meta.repositoryUrl, - homepage: "https://calckey.cloud", - }, - protocols: ["activitypub"], - services: { - inbound: [] as string[], - outbound: ["atom1.0", "rss2.0"], - }, - openRegistrations: !meta.disableRegistration, - usage: { - users: { total, activeHalfyear, activeMonth }, - localPosts, - localComments: 0, - }, - metadata: { - nodeName: meta.name, - nodeDescription: meta.description, - maintainer: { - name: meta.maintainerName, - email: meta.maintainerEmail, - }, - langs: meta.langs, - tosUrl: meta.ToSUrl, - repositoryUrl: meta.repositoryUrl, - feedbackUrl: meta.feedbackUrl, - disableRegistration: meta.disableRegistration, - disableLocalTimeline: meta.disableLocalTimeline, - disableRecommendedTimeline: meta.disableRecommendedTimeline, - disableGlobalTimeline: meta.disableGlobalTimeline, - emailRequiredForSignup: meta.emailRequiredForSignup, - enableHcaptcha: meta.enableHcaptcha, - enableRecaptcha: meta.enableRecaptcha, - maxNoteTextLength: MAX_NOTE_TEXT_LENGTH, - maxCaptionTextLength: MAX_CAPTION_TEXT_LENGTH, - enableTwitterIntegration: meta.enableTwitterIntegration, - enableGithubIntegration: meta.enableGithubIntegration, - enableDiscordIntegration: meta.enableDiscordIntegration, - enableEmail: meta.enableEmail, - enableServiceWorker: meta.enableServiceWorker, - proxyAccountName: proxyAccount ? proxyAccount.username : null, - themeColor: meta.themeColor || "#31748f", - }, - }; -}; - -const cache = new Cache<Awaited<ReturnType<typeof nodeinfo2>>>(1000 * 60 * 10); - -router.get(nodeinfo2_1path, async (ctx) => { - const base = await cache.fetch(null, () => nodeinfo2()); - - ctx.body = { version: "2.1", ...base }; - ctx.set("Cache-Control", "public, max-age=600"); -}); - -router.get(nodeinfo2_0path, async (ctx) => { - const base = await cache.fetch(null, () => nodeinfo2()); - - // @ts-ignore - base.software.repository = undefined; - - ctx.body = { version: "2.0", ...base }; - ctx.set("Cache-Control", "public, max-age=600"); -}); - -export default router; diff --git a/packages/backend/src/server/proxy/index.ts b/packages/backend/src/server/proxy/index.ts deleted file mode 100644 index 004b3779fb..0000000000 --- a/packages/backend/src/server/proxy/index.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Media Proxy - */ - -import Koa from "koa"; -import cors from "@koa/cors"; -import Router from "@koa/router"; -import { proxyMedia } from "./proxy-media.js"; - -// Init app -const app = new Koa(); -app.use(cors()); -app.use(async (ctx, next) => { - ctx.set( - "Content-Security-Policy", - `default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'`, - ); - await next(); -}); - -// Init router -const router = new Router(); - -router.get("/:url*", proxyMedia); - -// Register router -app.use(router.routes()); - -export default app; diff --git a/packages/backend/src/server/proxy/proxy-media.ts b/packages/backend/src/server/proxy/proxy-media.ts deleted file mode 100644 index a9c257bfeb..0000000000 --- a/packages/backend/src/server/proxy/proxy-media.ts +++ /dev/null @@ -1,105 +0,0 @@ -import * as fs from "node:fs"; -import type Koa from "koa"; -import sharp from "sharp"; -import type { IImage } from "@/services/drive/image-processor.js"; -import { convertToWebp } from "@/services/drive/image-processor.js"; -import { createTemp } from "@/misc/create-temp.js"; -import { downloadUrl } from "@/misc/download-url.js"; -import { detectType } from "@/misc/get-file-info.js"; -import { StatusError } from "@/misc/fetch.js"; -import { FILE_TYPE_BROWSERSAFE } from "@/const.js"; -import { serverLogger } from "../index.js"; -import { isMimeImage } from "@/misc/is-mime-image.js"; - -export async function proxyMedia(ctx: Koa.Context) { - const url = "url" in ctx.query ? ctx.query.url : `https://${ctx.params.url}`; - - if (typeof url !== "string") { - ctx.status = 400; - return; - } - - // Create temp file - const [path, cleanup] = await createTemp(); - - try { - await downloadUrl(url, path); - - const { mime, ext } = await detectType(path); - const isConvertibleImage = isMimeImage(mime, "sharp-convertible-image"); - - let image: IImage; - - if ("static" in ctx.query && isConvertibleImage) { - image = await convertToWebp(path, 996, 560); - } else if ("preview" in ctx.query && isConvertibleImage) { - image = await convertToWebp(path, 400, 400); - } else if ("badge" in ctx.query) { - if (!isConvertibleImage) { - // 画像でないなら404でお茶を濁す - throw new StatusError("Unexpected mime", 404); - } - - const mask = sharp(path) - .resize(96, 96, { - fit: "inside", - withoutEnlargement: false, - }) - .greyscale() - .normalise() - .linear(1.75, -(128 * 1.75) + 128) // 1.75x contrast - .flatten({ background: "#000" }) - .toColorspace("b-w"); - - const stats = await mask.clone().stats(); - - if (stats.entropy < 0.1) { - // エントロピーがあまりない場合は404にする - throw new StatusError("Skip to provide badge", 404); - } - - const data = sharp({ - create: { - width: 96, - height: 96, - channels: 4, - background: { r: 0, g: 0, b: 0, alpha: 0 }, - }, - }) - .pipelineColorspace("b-w") - .boolean(await mask.png().toBuffer(), "eor"); - - image = { - data: await data.png().toBuffer(), - ext: "png", - type: "image/png", - }; - } else if (mime === "image/svg+xml") { - image = await convertToWebp(path, 2048, 2048, 1); - } else if ( - !(mime.startsWith("image/") && FILE_TYPE_BROWSERSAFE.includes(mime)) - ) { - throw new StatusError("Rejected type", 403, "Rejected type"); - } else { - image = { - data: fs.readFileSync(path), - ext, - type: mime, - }; - } - - ctx.set("Content-Type", image.type); - ctx.set("Cache-Control", "max-age=31536000, immutable"); - ctx.body = image.data; - } catch (e) { - serverLogger.error(`${e}`); - - if (e instanceof StatusError && (e.statusCode === 302 || e.isClientError)) { - ctx.status = e.statusCode; - } else { - ctx.status = 500; - } - } finally { - cleanup(); - } -} diff --git a/packages/backend/src/server/web/bios.css b/packages/backend/src/server/web/bios.css deleted file mode 100644 index e79fc0657b..0000000000 --- a/packages/backend/src/server/web/bios.css +++ /dev/null @@ -1,147 +0,0 @@ -main > .tabs { - padding: 16px; - border-bottom: 4px solid #908caa; -} -#lsEditor > .adder { - margin: 16px; - padding: 16px; - border: 2px solid #908caa; -} -#lsEditor > .adder > textarea { - display: block; - width: 100%; - min-height: 5em; - box-sizing: border-box; -} -#lsEditor > .record { - padding: 16px; - border-bottom: 1px solid #908caa; -} -#lsEditor > .record > header { - font-weight: 700; -} -#lsEditor > .record > textarea { - display: block; - width: 100%; - min-height: 5em; - box-sizing: border-box; -} - -html { - background: #191724; -} -main { - background: #1f1d2e; - border-radius: 10px; -} -#tl > div { - padding: 16px; - border-bottom: 1px solid #908caa; -} -#tl > div > header { - font-weight: 700; -} - -* { - font-family: BIZ UDGothic, Roboto, HelveticaNeue, Arial, sans-serif; -} -#calckey_app { - display: none !important; -} -body, -html { - background-color: #191724; - color: #e0def4; - justify-content: center; - margin: auto; - padding: 10px; - text-align: center; -} -button { - border-radius: 999px; - padding: 0px 12px 0px 12px; - border: none; - cursor: pointer; - margin-bottom: 12px; - background: linear-gradient(90deg, rgb(156, 207, 216), rgb(49, 116, 143)); - line-height: 50px; - color: #191724; - font-weight: bold; - font-size: 20px; - padding: 12px; -} -button { - border-radius: 999px; - padding: 0px 12px 0px 12px; - border: none; - cursor: pointer; - margin-bottom: 12px; -} -button { - background: #444; - line-height: 40px; - color: rgb(156, 207, 216); - font-size: 16px; - padding: 0 20px; - margin-right: 5px; - margin-left: 5px; -} -button:hover { - background: #555; -} -#ls { - background: linear-gradient(90deg, rgb(156, 207, 216), rgb(49, 116, 143)); - line-height: 30px; - color: #191724; - font-weight: bold; - font-size: 18px; - padding: 12px; -} -#ls:hover { - background: rgb(156, 207, 216); -} -a { - color: rgb(156, 207, 216); - text-decoration: none; -} -p, -li { - font-size: 16px; -} - -h1 { - font-size: 32px; -} -code { - font-family: Fira, FiraCode, monospace; -} -textarea { - background-color: #444; - border: solid #aaa; - border-radius: 10px; - color: #e0def4; - margin-top: 1rem; - margin-bottom: 1rem; - width: 20rem; - height: 7.5rem; - padding: 0.5rem; -} - -textarea:focus { - border: solid #eee; -} -input { - background-color: #666; - border: solid #aaa; - border-radius: 10px; - color: #e0def4; - margin-top: 1rem; - margin-bottom: 1rem; - width: 10rem; - height: 1rem; - padding: 0.5rem; -} - -input:focus { - border: solid #eee; -} diff --git a/packages/backend/src/server/web/bios.js b/packages/backend/src/server/web/bios.js deleted file mode 100644 index e715a01068..0000000000 --- a/packages/backend/src/server/web/bios.js +++ /dev/null @@ -1,89 +0,0 @@ -"use strict"; - -window.onload = async () => { - const account = JSON.parse(localStorage.getItem("account")); - const i = account.token; - - const api = (endpoint, data = {}) => { - const promise = new Promise((resolve, reject) => { - // Append a credential - if (i) data.i = i; - - // Send request - fetch(endpoint.indexOf("://") > -1 ? endpoint : `/api/${endpoint}`, { - method: "POST", - body: JSON.stringify(data), - credentials: "omit", - cache: "no-cache", - }) - .then(async (res) => { - const body = res.status === 204 ? null : await res.json(); - - if (res.status === 200) { - resolve(body); - } else if (res.status === 204) { - resolve(); - } else { - reject(body.error); - } - }) - .catch(reject); - }); - - return promise; - }; - - const content = document.getElementById("content"); - - document.getElementById("ls").addEventListener("click", () => { - content.innerHTML = ""; - - const lsEditor = document.createElement("div"); - lsEditor.id = "lsEditor"; - - const adder = document.createElement("div"); - adder.classList.add("adder"); - const addKeyInput = document.createElement("input"); - const addValueTextarea = document.createElement("textarea"); - const addButton = document.createElement("button"); - addButton.textContent = "Add"; - addButton.addEventListener("click", () => { - localStorage.setItem(addKeyInput.value, addValueTextarea.value); - location.reload(); - }); - - adder.appendChild(addKeyInput); - adder.appendChild(addValueTextarea); - adder.appendChild(addButton); - lsEditor.appendChild(adder); - - for (let i = 0; i < localStorage.length; i++) { - const k = localStorage.key(i); - const record = document.createElement("div"); - record.classList.add("record"); - const header = document.createElement("header"); - header.textContent = k; - const textarea = document.createElement("textarea"); - textarea.textContent = localStorage.getItem(k); - const saveButton = document.createElement("button"); - saveButton.textContent = "Save"; - saveButton.addEventListener("click", () => { - localStorage.setItem(k, textarea.value); - location.reload(); - }); - const removeButton = document.createElement("button"); - removeButton.textContent = "Remove"; - removeButton.addEventListener("click", () => { - localStorage.removeItem(k); - location.reload(); - }); - record.appendChild(header); - record.appendChild(textarea); - record.appendChild(saveButton); - record.appendChild(removeButton); - lsEditor.appendChild(record); - } - - content.appendChild(lsEditor); - }); -}; diff --git a/packages/backend/src/server/web/boot.js b/packages/backend/src/server/web/boot.js deleted file mode 100644 index e7e859d20c..0000000000 --- a/packages/backend/src/server/web/boot.js +++ /dev/null @@ -1,319 +0,0 @@ -/** - * BOOT LOADER - * サーバーからレスポンスされるHTMLに埋め込まれるスクリプトで、以下の役割を持ちます。 - * - 翻訳ファイルをフェッチする。 - * - バージョンに基づいて適切なメインスクリプトを読み込む。 - * - キャッシュされたコンパイル済みテーマを適用する。 - * - クライアントの設定値に基づいて対応するHTMLクラス等を設定する。 - * テーマをこの段階で設定するのは、メインスクリプトが読み込まれる間もテーマを適用したいためです。 - * 注: webpackは介さないため、このファイルではrequireやimportは使えません。 - */ - -"use strict"; - -// ブロックの中に入れないと、定義した変数がブラウザのグローバルスコープに登録されてしまい邪魔なので -(async () => { - window.onerror = (e) => { - console.error(e); - renderError("SOMETHING_HAPPENED", e); - }; - window.onunhandledrejection = (e) => { - console.error(e); - renderError("SOMETHING_HAPPENED_IN_PROMISE", e); - }; - - //#region Detect language & fetch translations - const v = localStorage.getItem("v") || VERSION; - - const supportedLangs = LANGS; - let lang = localStorage.getItem("lang"); - if (lang == null || !supportedLangs.includes(lang)) { - if (supportedLangs.includes(navigator.language)) { - lang = navigator.language; - } else { - lang = supportedLangs.find((x) => x.split("-")[0] === navigator.language); - - // Fallback - if (lang == null) lang = "en-US"; - } - } - - const res = await fetch(`/assets/locales/${lang}.${v}.json`); - if (res.status === 200) { - localStorage.setItem("lang", lang); - localStorage.setItem("locale", await res.text()); - localStorage.setItem("localeVersion", v); - } else { - await checkUpdate(); - renderError("LOCALE_FETCH"); - return; - } - //#endregion - - //#region Script - function importAppScript() { - import(`/assets/${CLIENT_ENTRY}`).catch(async (e) => { - await checkUpdate(); - console.error(e); - renderError("APP_IMPORT", e); - }); - } - - // タイミングによっては、この時点でDOMの構築が済んでいる場合とそうでない場合とがある - if (document.readyState !== "loading") { - importAppScript(); - } else { - window.addEventListener("DOMContentLoaded", () => { - importAppScript(); - }); - } - //#endregion - - //#region Theme - const theme = localStorage.getItem("theme"); - if (theme) { - for (const [k, v] of Object.entries(JSON.parse(theme))) { - document.documentElement.style.setProperty(`--${k}`, v.toString()); - - // HTMLの theme-color 適用 - if (k === "htmlThemeColor") { - for (const tag of document.head.children) { - if ( - tag.tagName === "META" && - tag.getAttribute("name") === "theme-color" - ) { - tag.setAttribute("content", v); - break; - } - } - } - } - } - const colorSchema = localStorage.getItem("colorSchema"); - if (colorSchema) { - document.documentElement.style.setProperty("color-schema", colorSchema); - } - //#endregion - - const fontSize = localStorage.getItem("fontSize"); - if (fontSize) { - document.documentElement.classList.add("f-" + fontSize); - } - - const useSystemFont = localStorage.getItem("useSystemFont"); - if (useSystemFont) { - document.documentElement.classList.add("useSystemFont"); - } - - const wallpaper = localStorage.getItem("wallpaper"); - if (wallpaper) { - document.documentElement.style.backgroundImage = `url(${wallpaper})`; - } - - const customCss = localStorage.getItem("customCss"); - if (customCss && customCss.length > 0) { - const style = document.createElement("style"); - style.innerHTML = customCss; - document.head.appendChild(style); - } - - async function addStyle(styleText) { - let css = document.createElement("style"); - css.appendChild(document.createTextNode(styleText)); - document.head.appendChild(css); - } - - function renderError(code, details) { - let errorsElement = document.getElementById("errors"); - - if (!errorsElement) { - document.body.innerHTML = ` - <svg class="icon-warning" xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-alert-triangle" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> - <path stroke="none" d="M0 0h24v24H0z" fill="none"></path> - <path d="M12 9v2m0 4v.01"></path> - <path d="M5 19h14a2 2 0 0 0 1.84 -2.75l-7.1 -12.25a2 2 0 0 0 -3.5 0l-7.1 12.25a2 2 0 0 0 1.75 2.75"></path> - </svg> - <h1>An error has occurred!</h1> - <button class="button-big" onclick="location.reload(true);"> - <span class="button-label-big">Refresh</span> - </button> - <p class="dont-worry">Don't worry, it's (probably) not your fault.</p> - <p>Please make sure your browser is up-to-date and any AdBlockers are off.</p> - <p>If the problem persists after refreshing, please contact your instance's administrator.<br>You may also try the following options:</p> - <a href="/flush"> - <button class="button-small"> - <span class="button-label-small">Clear preferences and cache</span> - </button> - </a> - <br> - <a href="/cli"> - <button class="button-small"> - <span class="button-label-small">Start the simple client</span> - </button> - </a> - <br> - <a href="/bios"> - <button class="button-small"> - <span class="button-label-small">Start the repair tool</span> - </button> - </a> - <br> - <div id="errors"></div> - `; - errorsElement = document.getElementById("errors"); - } - const detailsElement = document.createElement("details"); - detailsElement.innerHTML = ` - <br> - <summary> - <code>ERROR CODE: ${code}</code> - </summary> - <code>${JSON.stringify(details)}</code>`; - errorsElement.appendChild(detailsElement); - addStyle(` - * { - font-family: BIZ UDGothic, Roboto, HelveticaNeue, Arial, sans-serif; - } - - #calckey_app, - #splash { - display: none !important; - } - - body, - html { - background-color: #191724; - color: #e0def4; - justify-content: center; - margin: auto; - padding: 10px; - text-align: center; - } - - button { - border-radius: 999px; - padding: 0px 12px 0px 12px; - border: none; - cursor: pointer; - margin-bottom: 12px; - } - - .button-big { - background: linear-gradient(90deg, rgb(196, 167, 231), rgb(235, 188, 186)); - line-height: 50px; - } - - .button-big:hover { - background: rgb(49, 116, 143); - } - - .button-small { - background: #444; - line-height: 40px; - } - - .button-small:hover { - background: #555; - } - - .button-label-big { - color: #191724; - font-weight: bold; - font-size: 20px; - padding: 12px; - } - - .button-label-small { - color: rgb(156, 207, 216); - font-size: 16px; - padding: 12px; - } - - a { - color: rgb(156, 207, 216); - text-decoration: none; - } - - p, - li { - font-size: 16px; - } - - .dont-worry, - #msg { - font-size: 18px; - } - - .icon-warning { - color: #f6c177; - height: 4rem; - padding-top: 2rem; - } - - h1 { - font-size: 32px; - } - - code { - font-family: Fira, FiraCode, monospace; - } - - details { - background: #1f1d2e; - margin-bottom: 2rem; - padding: 0.5rem 1rem; - width: 40rem; - border-radius: 10px; - justify-content: center; - margin: auto; - } - - summary { - cursor: pointer; - } - - summary > * { - display: inline; - } - - @media screen and (max-width: 500px) { - details { - width: 50%; - } - `); - } - - async function checkUpdate() { - try { - const res = await fetch("/api/meta", { - method: "POST", - cache: "no-cache", - }); - - const meta = await res.json(); - - if (meta.version != v) { - localStorage.setItem("v", meta.version); - refresh(); - } - } catch (e) { - console.error(e); - renderError("UPDATE_CHECK", e); - throw e; - } - } - - function refresh() { - // Clear cache (service worker) - try { - navigator.serviceWorker.controller.postMessage("clear"); - navigator.serviceWorker.getRegistrations().then((registrations) => { - registrations.forEach((registration) => registration.unregister()); - }); - } catch (e) { - console.error(e); - } - - location.reload(); - } -})(); diff --git a/packages/backend/src/server/web/cli.css b/packages/backend/src/server/web/cli.css deleted file mode 100644 index 460a7b7f31..0000000000 --- a/packages/backend/src/server/web/cli.css +++ /dev/null @@ -1,92 +0,0 @@ -html { - background: #191724; -} -main { - background: #1f1d2e; - border-radius: 10px; -} -#tl > div { - border: 1px solid #908caa; - border-radius: 10px; - margin: 10px; - padding: 10px; - width: fit-content; -} -#tl > div > header { - font-weight: 700; - display: inline-flex; -} - -img { - border-radius: 10px; - margin-right: 10px; -} - -#form { - text-align: center; -} - -#calckey_app { - display: none !important; -} - -body, -html { - font-family: BIZ UDGothic, Roboto, HelveticaNeue, Arial, sans-serif; - background-color: #191724; - color: #e0def4; - justify-content: center; - margin: auto; - padding: 10px; -} -button { - border-radius:999px; - padding:0 40px; - margin-top: 1rem; - border:none; - cursor:pointer; - margin-bottom:12px; - background:linear-gradient(90deg,#9ccfd8,#31748f); - line-height:50px; - color:#191724; - font-weight:700; - font-size:20px; - } -button:hover { - background: rgb(156, 207, 216); -} -a { - color: rgb(156, 207, 216); - text-decoration: none; -} -p, -li { - font-size: 16px; -} - -h1 { - font-size: 32px; -} -code { - font-family: Fira, FiraCode, monospace; -} -#text { - background-color: #444; - border: solid #aaa; - border-radius: 10px; - color: #e0def4; - margin-top: 3rem; - width: 20rem; - height: 5rem; - padding: 0.5rem; -} - -#text:focus { - border: solid #eee; -} - -@media screen and (max-width: 500px) { - #text { - width: 80% - } -} diff --git a/packages/backend/src/server/web/cli.js b/packages/backend/src/server/web/cli.js deleted file mode 100644 index 85a61a2446..0000000000 --- a/packages/backend/src/server/web/cli.js +++ /dev/null @@ -1,72 +0,0 @@ -"use strict"; - -window.onload = async () => { - const account = JSON.parse(localStorage.getItem("account")); - const i = account.token; - - const api = (endpoint, data = {}) => { - const promise = new Promise((resolve, reject) => { - // Append a credential - if (i) data.i = i; - - // Send request - fetch(endpoint.indexOf("://") > -1 ? endpoint : `/api/${endpoint}`, { - method: "POST", - body: JSON.stringify(data), - credentials: "omit", - cache: "no-cache", - }) - .then(async (res) => { - const body = res.status === 204 ? null : await res.json(); - - if (res.status === 200) { - resolve(body); - } else if (res.status === 204) { - resolve(); - } else { - reject(body.error); - } - }) - .catch(reject); - }); - - return promise; - }; - - document.getElementById("submit").addEventListener("click", () => { - api("notes/create", { - text: document.getElementById("text").value, - }).then(() => { - location.reload(); - }); - }); - - api("notes/timeline").then((notes) => { - const tl = document.getElementById("tl"); - for (const note of notes) { - const el = document.createElement("div"); - const header = document.createElement("header"); - const name = document.createElement("p"); - const avatar = document.createElement("img"); - name.textContent = `${note.user.name} @${note.user.username}`; - avatar.src = note.user.avatarUrl; - avatar.style = "height: 40px"; - const text = document.createElement("div"); - text.textContent = `${note.text}`; - el.appendChild(header); - header.appendChild(avatar); - header.appendChild(name); - if (note.text) { - el.appendChild(text); - } - if (note.files) { - for (const file of note.files) { - const img = document.createElement("img"); - img.src = file.properties.thumbnailUrl; - el.appendChild(img); - } - } - tl.appendChild(el); - } - }); -}; diff --git a/packages/backend/src/server/web/feed.ts b/packages/backend/src/server/web/feed.ts deleted file mode 100644 index 9cbeb28ae1..0000000000 --- a/packages/backend/src/server/web/feed.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { Feed } from "feed"; -import { In, IsNull } from "typeorm"; -import config from "@/config/index.js"; -import type { User } from "@/models/entities/user.js"; -import { Notes, DriveFiles, UserProfiles, Users } from "@/models/index.js"; - -export default async function (user: User) { - const author = { - link: `${config.url}/@${user.username}`, - name: user.name || user.username, - }; - - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - - const notes = await Notes.find({ - where: { - userId: user.id, - renoteId: IsNull(), - visibility: In(["public", "home"]), - }, - order: { createdAt: -1 }, - take: 20, - }); - - const feed = new Feed({ - id: author.link, - title: `${author.name} (@${user.username}@${config.host})`, - updated: notes[0].createdAt, - generator: "Calckey", - description: `${user.notesCount} Notes, ${ - profile.ffVisibility === "public" ? user.followingCount : "?" - } Following, ${ - profile.ffVisibility === "public" ? user.followersCount : "?" - } Followers${profile.description ? ` · ${profile.description}` : ""}`, - link: author.link, - image: await Users.getAvatarUrl(user), - feedLinks: { - json: `${author.link}.json`, - atom: `${author.link}.atom`, - }, - author, - copyright: user.name || user.username, - }); - - for (const note of notes) { - const files = - note.fileIds.length > 0 - ? await DriveFiles.findBy({ - id: In(note.fileIds), - }) - : []; - const file = files.find((file) => file.type.startsWith("image/")); - - feed.addItem({ - title: `New note by ${author.name}`, - link: `${config.url}/notes/${note.id}`, - date: note.createdAt, - description: note.cw || undefined, - content: note.text || undefined, - image: file ? DriveFiles.getPublicUrl(file) || undefined : undefined, - }); - } - - return feed; -} diff --git a/packages/backend/src/server/web/index.ts b/packages/backend/src/server/web/index.ts deleted file mode 100644 index 028170cd75..0000000000 --- a/packages/backend/src/server/web/index.ts +++ /dev/null @@ -1,677 +0,0 @@ -/** - * Web Client Server - */ - -import { dirname } from "node:path"; -import { fileURLToPath } from "node:url"; -import { readFileSync } from "node:fs"; -import Koa from "koa"; -import Router from "@koa/router"; -import send from "koa-send"; -import views from "koa-views"; -import sharp from "sharp"; -import { createBullBoard } from "@bull-board/api"; -import { BullAdapter } from "@bull-board/api/bullAdapter.js"; -import { KoaAdapter } from "@bull-board/koa"; -import { In, IsNull } from "typeorm"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import config from "@/config/index.js"; -import { - Users, - Notes, - UserProfiles, - Pages, - Channels, - Clips, - GalleryPosts, -} from "@/models/index.js"; -import * as Acct from "@/misc/acct.js"; -import { getNoteSummary } from "@/misc/get-note-summary.js"; -import { queues } from "@/queue/queues.js"; -import { genOpenapiSpec } from "../api/openapi/gen-spec.js"; -import { urlPreviewHandler } from "./url-preview.js"; -import { manifestHandler } from "./manifest.js"; -import packFeed from "./feed.js"; -import { MINUTE, DAY } from "@/const.js"; - -const _filename = fileURLToPath(import.meta.url); -const _dirname = dirname(_filename); - -const staticAssets = `${_dirname}/../../../assets/`; -const clientAssets = `${_dirname}/../../../../client/assets/`; -const assets = `${_dirname}/../../../../../built/_client_dist_/`; -const swAssets = `${_dirname}/../../../../../built/_sw_dist_/`; - -// Init app -const app = new Koa(); - -//#region Bull Dashboard -const bullBoardPath = "/queue"; - -// Authenticate -app.use(async (ctx, next) => { - if (ctx.path === bullBoardPath || ctx.path.startsWith(`${bullBoardPath}/`)) { - const token = ctx.cookies.get("token"); - if (token == null) { - ctx.status = 401; - return; - } - const user = await Users.findOneBy({ token }); - if (user == null || !(user.isAdmin || user.isModerator)) { - ctx.status = 403; - return; - } - } - await next(); -}); - -const serverAdapter = new KoaAdapter(); - -createBullBoard({ - queues: queues.map((q) => new BullAdapter(q)), - serverAdapter, -}); - -serverAdapter.setBasePath(bullBoardPath); -app.use(serverAdapter.registerPlugin()); -//#endregion - -// Init renderer -app.use( - views(`${_dirname}/views`, { - extension: "pug", - options: { - version: config.version, - getClientEntry: () => - process.env.NODE_ENV === "production" - ? config.clientEntry - : JSON.parse( - readFileSync( - `${_dirname}/../../../../../built/_client_dist_/manifest.json`, - "utf-8", - ), - )["src/init.ts"], - config, - }, - }), -); - -// Favicon Router -app.use(async (ctx, next) => { - if (ctx.path != "/favicon.ico") return next(); - const meta = await fetchMeta(); - if (meta.iconUrl === "") - ctx.body = readFileSync(`${_dirname}/../../../assets/favicon.ico`); - else ctx.redirect(meta.iconUrl); -}); - -// Common request handler -app.use(async (ctx, next) => { - // IFrameの中に入れられないようにする - ctx.set("X-Frame-Options", "DENY"); - await next(); -}); - -// Init router -const router = new Router(); - -//#region static assets - -router.get("/static-assets/(.*)", async (ctx) => { - await send(ctx as any, ctx.path.replace("/static-assets/", ""), { - root: staticAssets, - maxage: 7 * DAY, - }); -}); - -router.get("/client-assets/(.*)", async (ctx) => { - await send(ctx as any, ctx.path.replace("/client-assets/", ""), { - root: clientAssets, - maxage: 7 * DAY, - }); -}); - -router.get("/assets/(.*)", async (ctx) => { - await send(ctx as any, ctx.path.replace("/assets/", ""), { - root: assets, - maxage: 7 * DAY, - }); -}); - -// Apple touch icon -router.get("/apple-touch-icon.png", async (ctx) => { - await send(ctx as any, "/apple-touch-icon.png", { - root: staticAssets, - }); -}); - -router.get("/twemoji/(.*)", async (ctx) => { - const path = ctx.path.replace("/twemoji/", ""); - - if (!path.match(/^[0-9a-f-]+\.svg$/)) { - ctx.status = 404; - return; - } - - ctx.set( - "Content-Security-Policy", - "default-src 'none'; style-src 'unsafe-inline'", - ); - - await send(ctx as any, path, { - root: `${_dirname}/../../../node_modules/@discordapp/twemoji/dist/svg/`, - maxage: 30 * DAY, - }); -}); - -router.get("/twemoji-badge/(.*)", async (ctx) => { - const path = ctx.path.replace("/twemoji-badge/", ""); - - if (!path.match(/^[0-9a-f-]+\.png$/)) { - ctx.status = 404; - return; - } - - const mask = await sharp( - `${_dirname}/../../../node_modules/@discordapp/twemoji/dist/svg/${path.replace( - ".png", - "", - )}.svg`, - { density: 1000 }, - ) - .resize(488, 488) - .greyscale() - .normalise() - .linear(1.75, -(128 * 1.75) + 128) // 1.75x contrast - .flatten({ background: "#000" }) - .extend({ - top: 12, - bottom: 12, - left: 12, - right: 12, - background: "#000", - }) - .toColorspace("b-w") - .png() - .toBuffer(); - - const buffer = await sharp({ - create: { - width: 512, - height: 512, - channels: 4, - background: { r: 0, g: 0, b: 0, alpha: 0 }, - }, - }) - .pipelineColorspace("b-w") - .boolean(mask, "eor") - .resize(96, 96) - .png() - .toBuffer(); - - ctx.set( - "Content-Security-Policy", - "default-src 'none'; style-src 'unsafe-inline'", - ); - ctx.set("Cache-Control", "max-age=2592000"); - ctx.set("Content-Type", "image/png"); - ctx.body = buffer; -}); - -// ServiceWorker -router.get("/sw.js", async (ctx) => { - await send(ctx as any, "/sw.js", { - root: swAssets, - maxage: 10 * MINUTE, - }); -}); - -// Manifest -router.get("/manifest.json", manifestHandler); - -router.get("/robots.txt", async (ctx) => { - await send(ctx as any, "/robots.txt", { - root: staticAssets, - }); -}); - -//#endregion - -// Docs -router.get("/api-doc", async (ctx) => { - await send(ctx as any, "/redoc.html", { - root: staticAssets, - }); -}); - -// URL preview endpoint -router.get("/url", urlPreviewHandler); - -router.get("/api.json", async (ctx) => { - ctx.body = genOpenapiSpec(); -}); - -const getFeed = async (acct: string) => { - const meta = await fetchMeta(); - if (meta.privateMode) { - return; - } - const { username, host } = Acct.parse(acct); - const user = await Users.findOneBy({ - usernameLower: username.toLowerCase(), - host: host ?? IsNull(), - isSuspended: false, - }); - - return user && (await packFeed(user)); -}; - -// As the /@user[.json|.rss|.atom]/sub endpoint is complicated, we will use a regex to switch between them. -const reUser = new RegExp( - "^/@(?<user>[^/]+?)(?:.(?<feed>json|rss|atom))?(?:/(?<sub>[^/]+))?$", -); -router.get(reUser, async (ctx, next) => { - const groups = reUser.exec(ctx.originalUrl)?.groups; - if (!groups) { - await next(); - return; - } - - ctx.params = groups; - - console.log(ctx, ctx.params); - if (groups.feed) { - if (groups.sub) { - await next(); - return; - } - - switch (groups.feed) { - case "json": - await jsonFeed(ctx, next); - break; - case "rss": - await rssFeed(ctx, next); - break; - case "atom": - await atomFeed(ctx, next); - break; - } - return; - } - - await userPage(ctx, next); -}); - -// Atom -const atomFeed: Router.Middleware = async (ctx) => { - const feed = await getFeed(ctx.params.user); - - if (feed) { - ctx.set("Content-Type", "application/atom+xml; charset=utf-8"); - ctx.body = feed.atom1(); - } else { - ctx.status = 404; - } -}; - -// RSS -const rssFeed: Router.Middleware = async (ctx) => { - const feed = await getFeed(ctx.params.user); - - if (feed) { - ctx.set("Content-Type", "application/rss+xml; charset=utf-8"); - ctx.body = feed.rss2(); - } else { - ctx.status = 404; - } -}; - -// JSON -const jsonFeed: Router.Middleware = async (ctx) => { - const feed = await getFeed(ctx.params.user); - - if (feed) { - ctx.set("Content-Type", "application/json; charset=utf-8"); - ctx.body = feed.json1(); - } else { - ctx.status = 404; - } -}; - -//#region SSR (for crawlers) -// User -const userPage: Router.Middleware = async (ctx, next) => { - const userParam = ctx.params.user; - const subParam = ctx.params.sub; - const { username, host } = Acct.parse(userParam); - - const user = await Users.findOneBy({ - usernameLower: username.toLowerCase(), - host: host ?? IsNull(), - isSuspended: false, - }); - - if (user === null) { - await next(); - return; - } - - const profile = await UserProfiles.findOneByOrFail({ userId: user.id }); - const meta = await fetchMeta(); - const me = profile.fields - ? profile.fields - .filter((filed) => filed.value?.match(/^https?:/)) - .map((field) => field.value) - : []; - - const userDetail = { - user, - profile, - me, - avatarUrl: await Users.getAvatarUrl(user), - sub: subParam, - instanceName: meta.name || "Calckey", - icon: meta.iconUrl, - themeColor: meta.themeColor, - privateMode: meta.privateMode, - }; - - await ctx.render("user", userDetail); - ctx.set("Cache-Control", "public, max-age=15"); -}; - -router.get("/users/:user", async (ctx) => { - const user = await Users.findOneBy({ - id: ctx.params.user, - host: IsNull(), - isSuspended: false, - }); - - if (user == null) { - ctx.status = 404; - return; - } - - ctx.redirect(`/@${user.username}${user.host == null ? "" : `@${user.host}`}`); -}); - -// Note -router.get("/notes/:note", async (ctx, next) => { - const note = await Notes.findOneBy({ - id: ctx.params.note, - visibility: In(["public", "home"]), - }); - - if (note) { - const _note = await Notes.pack(note); - const profile = await UserProfiles.findOneByOrFail({ userId: note.userId }); - const meta = await fetchMeta(); - await ctx.render("note", { - note: _note, - profile, - avatarUrl: await Users.getAvatarUrl( - await Users.findOneByOrFail({ id: note.userId }), - ), - // TODO: Let locale changeable by instance setting - summary: getNoteSummary(_note), - instanceName: meta.name || "Calckey", - icon: meta.iconUrl, - privateMode: meta.privateMode, - themeColor: meta.themeColor, - }); - - ctx.set("Cache-Control", "public, max-age=15"); - - return; - } - - await next(); -}); - -router.get("/posts/:note", async (ctx, next) => { - const note = await Notes.findOneBy({ - id: ctx.params.note, - visibility: In(["public", "home"]), - }); - - if (note) { - const _note = await Notes.pack(note); - const profile = await UserProfiles.findOneByOrFail({ userId: note.userId }); - const meta = await fetchMeta(); - await ctx.render("note", { - note: _note, - profile, - avatarUrl: await Users.getAvatarUrl( - await Users.findOneByOrFail({ id: note.userId }), - ), - // TODO: Let locale changeable by instance setting - summary: getNoteSummary(_note), - instanceName: meta.name || "Calckey", - icon: meta.iconUrl, - privateMode: meta.privateMode, - themeColor: meta.themeColor, - }); - - ctx.set("Cache-Control", "public, max-age=15"); - - return; - } - - await next(); -}); - -// Page -router.get("/@:user/pages/:page", async (ctx, next) => { - const { username, host } = Acct.parse(ctx.params.user); - const user = await Users.findOneBy({ - usernameLower: username.toLowerCase(), - host: host ?? IsNull(), - }); - - if (user == null) return; - - const page = await Pages.findOneBy({ - name: ctx.params.page, - userId: user.id, - }); - - if (page) { - const _page = await Pages.pack(page); - const profile = await UserProfiles.findOneByOrFail({ userId: page.userId }); - const meta = await fetchMeta(); - await ctx.render("page", { - page: _page, - profile, - avatarUrl: await Users.getAvatarUrl( - await Users.findOneByOrFail({ id: page.userId }), - ), - instanceName: meta.name || "Calckey", - icon: meta.iconUrl, - themeColor: meta.themeColor, - privateMode: meta.privateMode, - }); - - if (["public"].includes(page.visibility)) { - ctx.set("Cache-Control", "public, max-age=15"); - } else { - ctx.set("Cache-Control", "private, max-age=0, must-revalidate"); - } - - return; - } - - await next(); -}); - -// Clip -// TODO: handling of private clips -router.get("/clips/:clip", async (ctx, next) => { - const clip = await Clips.findOneBy({ - id: ctx.params.clip, - }); - - if (clip) { - const _clip = await Clips.pack(clip); - const profile = await UserProfiles.findOneByOrFail({ userId: clip.userId }); - const meta = await fetchMeta(); - await ctx.render("clip", { - clip: _clip, - profile, - avatarUrl: await Users.getAvatarUrl( - await Users.findOneByOrFail({ id: clip.userId }), - ), - instanceName: meta.name || "Calckey", - privateMode: meta.privateMode, - icon: meta.iconUrl, - themeColor: meta.themeColor, - }); - - ctx.set("Cache-Control", "public, max-age=15"); - - return; - } - - await next(); -}); - -// Gallery post -router.get("/gallery/:post", async (ctx, next) => { - const post = await GalleryPosts.findOneBy({ id: ctx.params.post }); - - if (post) { - const _post = await GalleryPosts.pack(post); - const profile = await UserProfiles.findOneByOrFail({ userId: post.userId }); - const meta = await fetchMeta(); - await ctx.render("gallery-post", { - post: _post, - profile, - avatarUrl: await Users.getAvatarUrl( - await Users.findOneByOrFail({ id: post.userId }), - ), - instanceName: meta.name || "Calckey", - icon: meta.iconUrl, - themeColor: meta.themeColor, - privateMode: meta.privateMode, - }); - - ctx.set("Cache-Control", "public, max-age=15"); - - return; - } - - await next(); -}); - -// Channel -router.get("/channels/:channel", async (ctx, next) => { - const channel = await Channels.findOneBy({ - id: ctx.params.channel, - }); - - if (channel) { - const _channel = await Channels.pack(channel); - const meta = await fetchMeta(); - await ctx.render("channel", { - channel: _channel, - instanceName: meta.name || "Calckey", - icon: meta.iconUrl, - themeColor: meta.themeColor, - privateMode: meta.privateMode, - }); - - ctx.set("Cache-Control", "public, max-age=15"); - - return; - } - - await next(); -}); -//#endregion - -router.get("/_info_card_", async (ctx) => { - const meta = await fetchMeta(true); - if (meta.privateMode) { - ctx.status = 403; - return; - } - - ctx.remove("X-Frame-Options"); - - await ctx.render("info-card", { - version: config.version, - host: config.host, - meta: meta, - originalUsersCount: await Users.countBy({ host: IsNull() }), - originalNotesCount: await Notes.countBy({ userHost: IsNull() }), - }); -}); - -router.get("/bios", async (ctx) => { - await ctx.render("bios", { - version: config.version, - }); -}); - -router.get("/cli", async (ctx) => { - await ctx.render("cli", { - version: config.version, - }); -}); - -const override = (source: string, target: string, depth = 0) => - [ - undefined, - ...target.split("/").filter((x) => x), - ...source - .split("/") - .filter((x) => x) - .splice(depth), - ].join("/"); - -router.get("/flush", async (ctx) => { - await ctx.render("flush"); -}); - -// If a non-WebSocket request comes in to streaming and base html is returned with cache, the path will be cached by Proxy, etc. and it will be wrong. -router.get("/streaming", async (ctx) => { - ctx.status = 503; - ctx.set("Cache-Control", "private, max-age=0"); -}); -router.get("/api/v1/streaming", async (ctx) => { - ctx.status = 503; - ctx.set("Cache-Control", "private, max-age=0"); -}); - -// Render base html for all requests -router.get("(.*)", async (ctx) => { - const meta = await fetchMeta(); - let motd = ["Loading..."]; - if (meta.customMOTD.length > 0) { - motd = meta.customMOTD; - } - let splashIconUrl = meta.iconUrl; - if (meta.customSplashIcons.length > 0) { - splashIconUrl = - meta.customSplashIcons[ - Math.floor(Math.random() * meta.customSplashIcons.length) - ]; - } - await ctx.render("base", { - img: meta.bannerUrl, - title: meta.name || "Calckey", - instanceName: meta.name || "Calckey", - desc: meta.description, - icon: meta.iconUrl, - splashIcon: splashIconUrl, - themeColor: meta.themeColor, - randomMOTD: motd[Math.floor(Math.random() * motd.length)], - privateMode: meta.privateMode, - }); - ctx.set("Cache-Control", "public, max-age=3"); -}); - -// Register router -app.use(router.routes()); - -export default app; diff --git a/packages/backend/src/server/web/manifest.json b/packages/backend/src/server/web/manifest.json deleted file mode 100644 index 1e662fb202..0000000000 --- a/packages/backend/src/server/web/manifest.json +++ /dev/null @@ -1,74 +0,0 @@ -{ - "short_name": "Calckey", - "name": "Calckey", - "description": "An open source, decentralized social media platform that's free forever!", - "start_url": "/", - "display": "standalone", - "background_color": "#1f1d2e", - "theme_color": "#31748f", - "orientation": "portrait-primary", - "icons": [ - { - "src": "/static-assets/icons/192.png", - "sizes": "192x192", - "type": "image/png", - "purpose": "any" - }, - { - "src": "/static-assets/icons/512.png", - "sizes": "512x512", - "type": "image/png", - "purpose": "any" - }, - { - "src": "/static-assets/icons/maskable.png", - "sizes": "512x512", - "type": "image/png", - "purpose": "maskable" - }, - { - "src": "/static-assets/icons/monochrome.png", - "sizes": "512x512", - "type": "image/png", - "purpose": "monochrome" - } - ], - "share_target": { - "action": "/share/", - "params": { - "title": "title", - "text": "text", - "url": "url" - } - }, - "screenshots" : [ - { - "src": "/static-assets/screenshots/1.webp", - "sizes": "1195x579", - "type": "image/webp", - "platform": "narrow", - "label": "Profile page" - }, - { - "src": "/static-assets/screenshots/2.webp", - "sizes": "1195x579", - "type": "image/webp", - "platform": "narrow", - "label": "Posts" - } - ], - "shortcuts" : [ - { - "name": "Notifications", - "short_name": "Notifs", - "url": "/my/notifications" - }, - { - "name": "Chats", - "url": "/my/messaging" - } - ], - "categories": [ - "social" - ] -} diff --git a/packages/backend/src/server/web/manifest.ts b/packages/backend/src/server/web/manifest.ts deleted file mode 100644 index 31acc42f6b..0000000000 --- a/packages/backend/src/server/web/manifest.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type Koa from "koa"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import manifest from "./manifest.json" assert { type: "json" }; - -export const manifestHandler = async (ctx: Koa.Context) => { - // TODO - //const res = structuredClone(manifest); - const res = JSON.parse(JSON.stringify(manifest)); - - const instance = await fetchMeta(true); - - res.short_name = instance.name || "Calckey"; - res.name = instance.name || "Calckey"; - if (instance.themeColor) res.theme_color = instance.themeColor; - - ctx.set("Cache-Control", "max-age=300"); - ctx.body = res; -}; diff --git a/packages/backend/src/server/web/style.css b/packages/backend/src/server/web/style.css deleted file mode 100644 index ee42b9deba..0000000000 --- a/packages/backend/src/server/web/style.css +++ /dev/null @@ -1,127 +0,0 @@ -html, body { - background-color: var(--bg); - color: var(--fg); -} - -#splash { - position: fixed; - z-index: 10000; - top: 0; - left: 0; - width: 100vw; - height: 100vh; - cursor: wait; - background-color: var(--bg); - opacity: 1; - transition: opacity 0.2s ease; -} - -#splashIcon { - position: absolute; - top: 0; - right: 0; - bottom: 0; - left: 0; - margin: auto; - width: 64px; - height: 64px; - pointer-events: none; - animation-duration: 1s; - animation-iteration-count: infinite; - animation-name: tada; -} - -#splashSpinner { - position: absolute; - top: 0; - right: 0; - bottom: 0; - left: 0; - margin: auto; - display: inline-block; - width: 28px; - height: 28px; - transform: translateY(110px); - display: none; - color: var(--accent); -} -#splashSpinner > .spinner { - position: absolute; - top: 0; - left: 0; - width: 28px; - height: 28px; - fill-rule: evenodd; - clip-rule: evenodd; - stroke-linecap: round; - stroke-linejoin: round; - stroke-miterlimit: 1.5; -} -#splashSpinner > .spinner.bg { - opacity: 0.275; -} -#splashSpinner > .spinner.fg { - animation: splashSpinner 0.5s linear infinite; -} - -@keyframes splashSpinner { - 0% { - transform: rotate(0deg); - } - 100% { - transform: rotate(360deg); - } -} - -@keyframes tada { - 0% { - transform: scale3d(1, 1, 1); - } - - 10%, - 20% { - transform: scale3d(0.9, 0.9, 0.9) rotate3d(0, 0, 1, -3deg); - } - - 30%, - 50%, - 70%, - 90% { - transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, 3deg); - } - - 40%, - 60%, - 80% { - transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, -3deg); - } - - 100% { - transform: scale3d(1, 1, 1); - } -} - -@media(prefers-reduced-motion) { - #splashSpinner { - display: block; - } - - #splashIcon { - animation: none; - } -} - -#splashText { - position: absolute; - top: 0; - right: 0; - bottom: 0; - left: 0; - margin: auto; - display: inline-block; - width: 70%; - height: 0; - text-align: center; - padding-top: 100px; - font-family: sans-serif; -} diff --git a/packages/backend/src/server/web/url-preview.ts b/packages/backend/src/server/web/url-preview.ts deleted file mode 100644 index c9f3b6cac9..0000000000 --- a/packages/backend/src/server/web/url-preview.ts +++ /dev/null @@ -1,88 +0,0 @@ -import type Koa from "koa"; -import summaly from "summaly"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import Logger from "@/services/logger.js"; -import config from "@/config/index.js"; -import { query } from "@/prelude/url.js"; -import { getJson } from "@/misc/fetch.js"; - -const logger = new Logger("url-preview"); - -export const urlPreviewHandler = async (ctx: Koa.Context) => { - const url = ctx.query.url; - if (typeof url !== "string") { - ctx.status = 400; - return; - } - - const lang = ctx.query.lang; - if (Array.isArray(lang)) { - ctx.status = 400; - return; - } - - const meta = await fetchMeta(); - - logger.info( - meta.summalyProxy - ? `(Proxy) Getting preview of ${url}@${lang} ...` - : `Getting preview of ${url}@${lang} ...`, - ); - - try { - const summary = meta.summalyProxy - ? await getJson( - `${meta.summalyProxy}?${query({ - url: url, - lang: lang ?? "en-US", - })}`, - ) - : await summaly.default(url, { - followRedirects: false, - lang: lang ?? "en-US", - }); - - logger.succ(`Got preview of ${url}: ${summary.title}`); - - if ( - summary.url && - !(summary.url.startsWith("http://") || summary.url.startsWith("https://")) - ) { - throw new Error("unsupported schema included"); - } - - if ( - summary.player?.url && - !( - summary.player.url.startsWith("http://") || - summary.player.url.startsWith("https://") - ) - ) { - throw new Error("unsupported schema included"); - } - - summary.icon = wrap(summary.icon); - summary.thumbnail = wrap(summary.thumbnail); - - // Cache 7days - ctx.set("Cache-Control", "max-age=604800, immutable"); - - ctx.body = summary; - } catch (err) { - logger.warn(`Failed to get preview of ${url}: ${err}`); - ctx.status = 200; - ctx.set("Cache-Control", "max-age=86400, immutable"); - ctx.body = "{}"; - } -}; - -function wrap(url?: string): string | null { - return url != null - ? url.match(/^https?:\/\//) - ? `${config.url}/proxy/preview.webp?${query({ - url, - preview: "1", - })}` - : url - : null; -} diff --git a/packages/backend/src/server/web/views/base.pug b/packages/backend/src/server/web/views/base.pug deleted file mode 100644 index b5841883bd..0000000000 --- a/packages/backend/src/server/web/views/base.pug +++ /dev/null @@ -1,96 +0,0 @@ -block vars - -block loadClientEntry - - const clientEntry = getClientEntry(); - -doctype html - -// - - - ___ _ _ - / __\__ _| | ___| | _____ _ _ - / / / _` | |/ __| |/ / _ \ | | | - / /__| (_| | | (__| < __/ |_| | - \____/\__,_|_|\___|_|\_\___|\__, | - (___/ - - Thank you for using Calckey! - If you are reading this message... how about joining the development? - https://codeberg.org/calckey/calckey - -html - - - var timestamp = Date.now(); - - head - meta(charset='utf-8') - meta(name='application-name' content='Calckey') - meta(name='referrer' content='origin') - meta(name='darkreader-lock' content='') - meta(name='theme-color' content= themeColor || '#31748f') - meta(name='theme-color-orig' content= themeColor || '#31748f') - meta(property='twitter:card' content='summary') - meta(property='og:site_name' content= instanceName || 'Calckey') - meta(name='viewport' content='width=device-width, initial-scale=1') - link(rel='icon' href= icon || `/favicon.ico?${ timestamp }`) - link(rel='apple-touch-icon' href= icon || `/apple-touch-icon.png?${ timestamp }`) - link(rel='manifest' href='/manifest.json') - link(rel='prefetch' href=`/static-assets/badges/info.png?${ timestamp }`) - link(rel='prefetch' href=`/static-assets/badges/not-found.png?${ timestamp }`) - link(rel='prefetch' href=`/static-assets/badges/error.png?${ timestamp }`) - link(rel='stylesheet' href=`/static-assets/instance.css?${ timestamp }`) - link(rel='modulepreload' href=`/assets/${clientEntry.file}`) - - if Array.isArray(clientEntry.css) - each href in clientEntry.css - link(rel='stylesheet' href=`/assets/${href}`) - - title - block title - = title || 'Calckey' - - block desc - meta(name='description' content=desc || 'An open source, decentralized social media platform that\'s free forever! 🚀') - - block meta - if privateMode - meta(name='robots' content='noindex') - - block og - meta(property='og:title' content=title || 'Calckey') - meta(property='og:description' content=desc || 'An open source, decentralized social media platform that\'s free forever! 🚀') - meta(property='og:image' content=img) - meta(property='og:image:alt' content=alt || 'Pfp') - - style - include ../style.css - - script. - var VERSION = "#{version}"; - var CLIENT_ENTRY = "#{clientEntry.file}"; - - script - include ../boot.js - - body - noscript: p - | JavaScriptを有効にしてください - br - | Please turn on your JavaScript - div#splash - img#splashIcon(src= splashIcon || `/static-assets/splash.png?${ timestamp }`) - span#splashText - block randomMOTD - = randomMOTD - div#splashSpinner - <svg class="spinner bg" viewBox="0 0 152 152" xmlns="http://www.w3.org/2000/svg"> - <g transform="matrix(1,0,0,1,12,12)"> - <circle cx="64" cy="64" r="64" style="fill:none;stroke:currentColor;stroke-width:24px;"/> - </g> - </svg> - <svg class="spinner fg" viewBox="0 0 152 152" xmlns="http://www.w3.org/2000/svg"> - <g transform="matrix(1,0,0,1,12,12)"> - <path d="M128,64C128,28.654 99.346,0 64,0C99.346,0 128,28.654 128,64Z" style="fill:none;stroke:currentColor;stroke-width:24px;"/> - </g> - </svg> - block content diff --git a/packages/backend/src/server/web/views/bios.pug b/packages/backend/src/server/web/views/bios.pug deleted file mode 100644 index 408ebb27b1..0000000000 --- a/packages/backend/src/server/web/views/bios.pug +++ /dev/null @@ -1,21 +0,0 @@ -doctype html - -html - - head - meta(charset='utf-8') - meta(name='application-name' content='Calckey') - meta(name='viewport' content='width=device-width, initial-scale=1.0') - title Calckey Repair Tool - style - include ../bios.css - script - include ../bios.js - - body - header - h1 Calckey Repair Tool v#{version} - main - div.tabs - button#ls Edit local storage - div#content diff --git a/packages/backend/src/server/web/views/channel.pug b/packages/backend/src/server/web/views/channel.pug deleted file mode 100644 index c4594b7666..0000000000 --- a/packages/backend/src/server/web/views/channel.pug +++ /dev/null @@ -1,20 +0,0 @@ -extends ./base - -block vars - - const title = privateMode ? instanceName : channel.name; - - const url = `${config.url}/channels/${channel.id}`; - -block title - = `${title} | ${instanceName}` - -block desc - unless privateMode - meta(name='description' content=channel.description) - -block og - unless privateMode - meta(property='og:type' content='article') - meta(property='og:title' content= title) - meta(property='og:description' content= channel.description) - meta(property='og:url' content= url) - meta(property='og:image' content= channel.bannerUrl) diff --git a/packages/backend/src/server/web/views/cli.pug b/packages/backend/src/server/web/views/cli.pug deleted file mode 100644 index 2abd5ae950..0000000000 --- a/packages/backend/src/server/web/views/cli.pug +++ /dev/null @@ -1,23 +0,0 @@ -doctype html - -html - - head - meta(charset='utf-8') - meta(name='application-name' content='Calckey') - meta(name='viewport' content='width=device-width, initial-scale=1.0') - title Calckey Cli - style - include ../cli.css - script - include ../cli.js - - body - header - h1 Calckey Simple Client v#{version} - main - div#form - textarea#text - br - button#submit Post - div#tl diff --git a/packages/backend/src/server/web/views/clip.pug b/packages/backend/src/server/web/views/clip.pug deleted file mode 100644 index 2432470c10..0000000000 --- a/packages/backend/src/server/web/views/clip.pug +++ /dev/null @@ -1,34 +0,0 @@ -extends ./base - -block vars - - const user = clip.user; - - const title = privateMode ? instanceName : clip.name; - - const url = `${config.url}/clips/${clip.id}`; - -block title - = `${title} | ${instanceName}` - -block desc - unless privateMode - meta(name='description' content= clip.description) - -block og - unless privateMode - meta(property='og:type' content='article') - meta(property='og:title' content= title) - meta(property='og:description' content= clip.description) - meta(property='og:url' content= url) - meta(property='og:image' content= avatarUrl) - -block meta - unless privateMode - if profile.noCrawle - meta(name='robots' content='noindex') - - meta(name='misskey:user-username' content=user.username) - meta(name='misskey:user-id' content=user.id) - meta(name='misskey:clip-id' content=clip.id) - - // todo - if user.twitter - meta(name='twitter:creator' content=`@${user.twitter.screenName}`) diff --git a/packages/backend/src/server/web/views/flush.pug b/packages/backend/src/server/web/views/flush.pug deleted file mode 100644 index c3de247270..0000000000 --- a/packages/backend/src/server/web/views/flush.pug +++ /dev/null @@ -1,71 +0,0 @@ -doctype html - -html - head - meta(charset='utf-8') - meta(name='application-name' content='Calckey') - meta(name='viewport' content='width=device-width, initial-scale=1.0') - title Flush Calckey - style. - * { - font-family: BIZ UDGothic, Roboto, HelveticaNeue, Arial, sans-serif; - } - body, - html { - background-color: #191724; - color: #e0def4; - justify-content: center; - margin: auto; - padding: 10px; - text-align: center; - } - a { - color: rgb(156, 207, 216); - text-decoration: none; - } - - body - #msg - script. - const msg = document.getElementById('msg'); - const successText = `\nSuccess Flush! <a href="/">Back to Calckey</a>\n成功しました。<a href="/">Calckeyを開き直してください。</a>`; - - message('Start flushing.'); - - (async function() { - try { - localStorage.clear(); - message('localStorage cleared.'); - - const idbPromises = ['MisskeyClient', 'keyval-store'].map((name, i, arr) => new Promise((res, rej) => { - const delidb = indexedDB.deleteDatabase(name); - delidb.onsuccess = () => res(message(`indexedDB "${name}" cleared. (${i + 1}/${arr.length})`)); - delidb.onerror = e => rej(e) - })); - - await Promise.all(idbPromises); - - if (navigator.serviceWorker.controller) { - navigator.serviceWorker.controller.postMessage('clear'); - await navigator.serviceWorker.getRegistrations() - .then(registrations => { - return Promise.all(registrations.map(registration => registration.unregister())); - }) - .catch(e => { throw new Error(e) }); - } - - message(successText); - } catch (e) { - message(`\n${e}\n\nFlush Failed. <a href="/flush">Please retry.</a>\n失敗しました。<a href="/flush">もう一度試してみてください。</a>`); - message(`\nIf you retry more than 3 times, clear the browser cache or contact to instance admin.\n3回以上試しても失敗する場合、ブラウザのキャッシュを消去し、それでもだめならインスタンス管理者に連絡してみてください。\n`) - - console.error(e); - setTimeout(() => { - location = '/'; - }, 10000) - } - })(); - - function message(text) { - msg.insertAdjacentHTML('beforeend', `<p>[${(new Date()).toString()}] ${text.replace(/\n/g,'<br>')}</p>`) - } diff --git a/packages/backend/src/server/web/views/gallery-post.pug b/packages/backend/src/server/web/views/gallery-post.pug deleted file mode 100644 index 1b1c2fbfbd..0000000000 --- a/packages/backend/src/server/web/views/gallery-post.pug +++ /dev/null @@ -1,36 +0,0 @@ -extends ./base - -block vars - - const user = post.user; - - const title = privateMode ? instanceName : post.title; - - const url = `${config.url}/gallery/${post.id}`; - -block title - = `${title} | ${instanceName}` - -block desc - unless privateMode - meta(name='description' content= post.description) - -block og - unless privateMode - meta(property='og:type' content='article') - meta(property='og:title' content= title) - meta(property='og:description' content= post.description) - meta(property='og:url' content= url) - meta(property='og:image' content= post.files[0].thumbnailUrl) - -block meta - unless privateMode - if user.host || profile.noCrawle - meta(name='robots' content='noindex') - - meta(name='misskey:user-username' content=user.username) - meta(name='misskey:user-id' content=user.id) - - // todo - if user.twitter - meta(name='twitter:creator' content=`@${user.twitter.screenName}`) - - if !user.host - link(rel='alternate' href=url type='application/activity+json') diff --git a/packages/backend/src/server/web/views/info-card.pug b/packages/backend/src/server/web/views/info-card.pug deleted file mode 100644 index be52d0c39f..0000000000 --- a/packages/backend/src/server/web/views/info-card.pug +++ /dev/null @@ -1,50 +0,0 @@ -doctype html - -html - - head - meta(charset='utf-8') - meta(name='application-name' content='Calckey') - title= meta.name || host - style. - html, body { - margin: 0; - padding: 0; - min-height: 100vh; - background: #fff; - } - - #a { - display: block; - } - - #banner { - background-size: cover; - background-position: center center; - } - - #title { - display: inline-block; - margin: 24px; - padding: 0.5em 0.8em; - color: #fff; - background: rgba(0, 0, 0, 0.5); - font-weight: bold; - font-size: 1.3em; - } - - #content { - overflow: auto; - color: #353c3e; - } - - #description { - margin: 24px; - } - - body - a#a(href=`https://${host}` target="_blank") - header#banner(style=`background-image: url(${meta.bannerUrl})`) - div#title= meta.name || host - div#content - div#description= meta.description diff --git a/packages/backend/src/server/web/views/note.pug b/packages/backend/src/server/web/views/note.pug deleted file mode 100644 index 476d42d9e8..0000000000 --- a/packages/backend/src/server/web/views/note.pug +++ /dev/null @@ -1,56 +0,0 @@ -extends ./base - -block vars - - const user = note.user; - - const title = privateMode ? instanceName : (user.name ? `${user.name} (@${user.username}${user.host ? `@${user.host}` : ''})` : `@${user.username}`); - - const url = `${config.url}/notes/${note.id}`; - - const isRenote = note.renote && note.text == null && note.fileIds.length == 0 && note.poll == null; - - const isImage = note.files.length !== 0 && note.files[0].type.startsWith('image'); - - const isVideo = note.files.length !== 0 && note.files[0].type.startsWith('video'); - - const imageUrl = isImage ? note.files[0].url : isVideo ? note.files[0].thumbnailUrl : avatarUrl; - -block title - = `${title} | ${instanceName}` - -block desc - unless privateMode - meta(name='description' content= summary) - -block og - unless privateMode - meta(property='og:type' content='article') - meta(property='og:title' content= title) - meta(property='og:description' content= summary) - meta(property='og:url' content= url) - meta(property='og:image' content= imageUrl) - if isImage && !note.files[0].isSensitive - meta(property='og:image:width' content=note.files[0].properties.width) - meta(property='og:image:height' content=note.files[0].properties.height) - meta(property='og:image:type' content=note.files[0].type) - meta(property='twitter:card' content="summary_large_image") - if isVideo - meta(property='og:video:type' content=note.files[0].type) - meta(property='og:video' content=note.files[0].url) - -block meta - unless privateMode - if user.host || isRenote || profile.noCrawle - meta(name='robots' content='noindex') - - meta(name='misskey:user-username' content=user.username) - meta(name='misskey:user-id' content=user.id) - meta(name='misskey:note-id' content=note.id) - - // todo - if user.twitter - meta(name='twitter:creator' content=`@${user.twitter.screenName}`) - - if note.prev - link(rel='prev' href=`${config.url}/notes/${note.prev}`) - if note.next - link(rel='next' href=`${config.url}/notes/${note.next}`) - - if !user.host - link(rel='alternate' href=url type='application/activity+json') - if note.uri - link(rel='alternate' href=note.uri type='application/activity+json') diff --git a/packages/backend/src/server/web/views/page.pug b/packages/backend/src/server/web/views/page.pug deleted file mode 100644 index 1095282131..0000000000 --- a/packages/backend/src/server/web/views/page.pug +++ /dev/null @@ -1,34 +0,0 @@ -extends ./base - -block vars - - const user = page.user; - - const title = privateMode ? instanceName : page.title; - - const url = `${config.url}/@${user.username}/${page.name}`; - -block title - = `${title} | ${instanceName}` - -block desc - unless privateMode - meta(name='description' content= page.summary) - -block og - unless privateMode - meta(property='og:type' content='article') - meta(property='og:title' content= title) - meta(property='og:description' content= page.summary) - meta(property='og:url' content= url) - meta(property='og:image' content= page.eyeCatchingImage ? page.eyeCatchingImage.thumbnailUrl : avatarUrl) - -block meta - unless privateMode - if profile.noCrawle - meta(name='robots' content='noindex') - - meta(name='misskey:user-username' content=user.username) - meta(name='misskey:user-id' content=user.id) - meta(name='misskey:page-id' content=page.id) - - // todo - if user.twitter - meta(name='twitter:creator' content=`@${user.twitter.screenName}`) diff --git a/packages/backend/src/server/web/views/user.pug b/packages/backend/src/server/web/views/user.pug deleted file mode 100644 index cc14dedb3a..0000000000 --- a/packages/backend/src/server/web/views/user.pug +++ /dev/null @@ -1,42 +0,0 @@ -extends ./base - -block vars - - const title = privateMode ? instanceName : (user.name ? `${user.name} (@${user.username})` : `@${user.username}`); - - const url = `${config.url}/@${(user.host ? `${user.username}@${user.host}` : user.username)}`; - -block title - = `${title} | ${instanceName}` - -block desc - unless privateMode - meta(name='description' content= profile.description) - -block og - unless privateMode - meta(property='og:type' content='blog') - meta(property='og:title' content= title) - meta(property='og:description' content= profile.description) - meta(property='og:url' content= url) - meta(property='og:image' content= avatarUrl) - -block meta - unless privateMode - if user.host || profile.noCrawle - meta(name='robots' content='noindex') - - meta(name='misskey:user-username' content=user.username) - meta(name='misskey:user-id' content=user.id) - - if profile.twitter - meta(name='twitter:creator' content=`@${profile.twitter.screenName}`) - - if !sub - if !user.host - link(rel='alternate' href=`${config.url}/users/${user.id}` type='application/activity+json') - if user.uri - link(rel='alternate' href=user.uri type='application/activity+json') - if profile.url - link(rel='alternate' href=profile.url type='text/html') - - each m in me - link(rel='me' href=`${m}`) diff --git a/packages/backend/src/server/well-known.ts b/packages/backend/src/server/well-known.ts deleted file mode 100644 index 5af3b2c84b..0000000000 --- a/packages/backend/src/server/well-known.ts +++ /dev/null @@ -1,191 +0,0 @@ -import Router from "@koa/router"; - -import config from "@/config/index.js"; -import * as Acct from "@/misc/acct.js"; -import { links } from "./nodeinfo.js"; -import { escapeAttribute, escapeValue } from "@/prelude/xml.js"; -import { Users } from "@/models/index.js"; -import type { User } from "@/models/entities/user.js"; -import type { FindOptionsWhere } from "typeorm"; -import { IsNull } from "typeorm"; - -// Init router -const router = new Router(); - -const XRD = ( - ...x: { - element: string; - value?: string; - attributes?: Record<string, string>; - }[] -) => - `<?xml version="1.0" encoding="UTF-8"?><XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">${x - .map( - ({ element, value, attributes }) => - `<${Object.entries( - (typeof attributes === "object" && attributes) || {}, - ).reduce((a, [k, v]) => `${a} ${k}="${escapeAttribute(v)}"`, element)}${ - typeof value === "string" ? `>${escapeValue(value)}</${element}` : "/" - }>`, - ) - .reduce((a, c) => a + c, "")}</XRD>`; - -const allPath = "/.well-known/(.*)"; -const webFingerPath = "/.well-known/webfinger"; -const jrd = "application/jrd+json"; -const xrd = "application/xrd+xml"; - -router.use(allPath, async (ctx, next) => { - ctx.set({ - "Access-Control-Allow-Headers": "Accept", - "Access-Control-Allow-Methods": "GET, OPTIONS", - "Access-Control-Allow-Origin": "*", - "Access-Control-Expose-Headers": "Vary", - }); - await next(); -}); - -router.options(allPath, async (ctx) => { - ctx.status = 204; -}); - -router.get("/.well-known/host-meta", async (ctx) => { - ctx.set("Content-Type", xrd); - ctx.body = XRD({ - element: "Link", - attributes: { - rel: "lrdd", - type: xrd, - template: `${config.url}${webFingerPath}?resource={uri}`, - }, - }); -}); - -router.get("/.well-known/host-meta.json", async (ctx) => { - ctx.set("Content-Type", jrd); - ctx.body = { - links: [ - { - rel: "lrdd", - type: jrd, - template: `${config.url}${webFingerPath}?resource={uri}`, - }, - ], - }; -}); - -if (config.twa != null) { - router.get("/.well-known/assetlinks.json", async (ctx) => { - ctx.set("Content-Type", "application/json"); - ctx.body = [ - { - relation: ["delegate_permission/common.handle_all_urls"], - target: { - namespace: config.twa.nameSpace, - package_name: config.twa.packageName, - sha256_cert_fingerprints: config.twa.sha256CertFingerprints, - }, - }, - ]; - }); -} - -router.get("/.well-known/nodeinfo", async (ctx) => { - ctx.body = { links }; -}); - -/* TODO -router.get('/.well-known/change-password', async ctx => { -}); -*/ - -router.get(webFingerPath, async (ctx) => { - const fromId = (id: User["id"]): FindOptionsWhere<User> => ({ - id, - host: IsNull(), - isSuspended: false, - }); - - const generateQuery = (resource: string): FindOptionsWhere<User> | number => - resource.startsWith(`${config.url.toLowerCase()}/users/`) - ? fromId(resource.split("/").pop()!) - : fromAcct( - Acct.parse( - resource.startsWith(`${config.url.toLowerCase()}/@`) - ? resource.split("/").pop()! - : resource.startsWith("acct:") - ? resource.slice("acct:".length) - : resource, - ), - ); - - const fromAcct = (acct: Acct.Acct): FindOptionsWhere<User> | number => - !acct.host || acct.host === config.host.toLowerCase() - ? { - usernameLower: acct.username, - host: IsNull(), - isSuspended: false, - } - : 422; - - if (typeof ctx.query.resource !== "string") { - ctx.status = 400; - return; - } - - const query = generateQuery(ctx.query.resource.toLowerCase()); - - if (typeof query === "number") { - ctx.status = query; - return; - } - - const user = await Users.findOneBy(query); - - if (user == null) { - ctx.status = 404; - return; - } - - const subject = `acct:${user.username}@${config.host}`; - const self = { - rel: "self", - type: "application/activity+json", - href: `${config.url}/users/${user.id}`, - }; - const profilePage = { - rel: "http://webfinger.net/rel/profile-page", - type: "text/html", - href: `${config.url}/@${user.username}`, - }; - const subscribe = { - rel: "http://ostatus.org/schema/1.0/subscribe", - template: `${config.url}/authorize-follow?acct={uri}`, - }; - - if (ctx.accepts(jrd, xrd) === xrd) { - ctx.body = XRD( - { element: "Subject", value: subject }, - { element: "Link", attributes: self }, - { element: "Link", attributes: profilePage }, - { element: "Link", attributes: subscribe }, - ); - ctx.type = xrd; - } else { - ctx.body = { - subject, - links: [self, profilePage, subscribe], - }; - ctx.type = jrd; - } - - ctx.vary("Accept"); - ctx.set("Cache-Control", "public, max-age=180"); -}); - -// Return 404 for other .well-known -router.all(allPath, async (ctx) => { - ctx.status = 404; -}); - -export default router; diff --git a/packages/backend/src/services/add-note-to-antenna.ts b/packages/backend/src/services/add-note-to-antenna.ts deleted file mode 100644 index 38979acb40..0000000000 --- a/packages/backend/src/services/add-note-to-antenna.ts +++ /dev/null @@ -1,61 +0,0 @@ -import type { Antenna } from "@/models/entities/antenna.js"; -import type { Note } from "@/models/entities/note.js"; -import { AntennaNotes, Mutings, Notes } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import { isUserRelated } from "@/misc/is-user-related.js"; -import { publishAntennaStream, publishMainStream } from "@/services/stream.js"; -import type { User } from "@/models/entities/user.js"; - -export async function addNoteToAntenna( - antenna: Antenna, - note: Note, - noteUser: { id: User["id"] }, -) { - // 通知しない設定になっているか、自分自身の投稿なら既読にする - const read = !antenna.notify || antenna.userId === noteUser.id; - - AntennaNotes.insert({ - id: genId(), - antennaId: antenna.id, - noteId: note.id, - read: read, - }); - - publishAntennaStream(antenna.id, "note", note); - - if (!read) { - const mutings = await Mutings.find({ - where: { - muterId: antenna.userId, - }, - select: ["muteeId"], - }); - - // Copy - const _note: Note = { - ...note, - }; - - if (note.replyId != null) { - _note.reply = await Notes.findOneByOrFail({ id: note.replyId }); - } - if (note.renoteId != null) { - _note.renote = await Notes.findOneByOrFail({ id: note.renoteId }); - } - - if (isUserRelated(_note, new Set<string>(mutings.map((x) => x.muteeId)))) { - return; - } - - // 2秒経っても既読にならなかったら通知 - setTimeout(async () => { - const unread = await AntennaNotes.findOneBy({ - antennaId: antenna.id, - read: false, - }); - if (unread) { - publishMainStream(antenna.userId, "unreadAntenna", antenna); - } - }, 2000); - } -} diff --git a/packages/backend/src/services/blocking/create.ts b/packages/backend/src/services/blocking/create.ts deleted file mode 100644 index 60bd6e9431..0000000000 --- a/packages/backend/src/services/blocking/create.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { publishMainStream, publishUserEvent } from "@/services/stream.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import renderFollow from "@/remote/activitypub/renderer/follow.js"; -import renderUndo from "@/remote/activitypub/renderer/undo.js"; -import { renderBlock } from "@/remote/activitypub/renderer/block.js"; -import { deliver } from "@/queue/index.js"; -import renderReject from "@/remote/activitypub/renderer/reject.js"; -import type { Blocking } from "@/models/entities/blocking.js"; -import type { User } from "@/models/entities/user.js"; -import { - Blockings, - Users, - FollowRequests, - Followings, - UserListJoinings, - UserLists, -} from "@/models/index.js"; -import { perUserFollowingChart } from "@/services/chart/index.js"; -import { genId } from "@/misc/gen-id.js"; -import { IdentifiableError } from "@/misc/identifiable-error.js"; -import { getActiveWebhooks } from "@/misc/webhook-cache.js"; -import { webhookDeliver } from "@/queue/index.js"; - -export default async function (blocker: User, blockee: User) { - await Promise.all([ - cancelRequest(blocker, blockee), - cancelRequest(blockee, blocker), - unFollow(blocker, blockee), - unFollow(blockee, blocker), - removeFromList(blockee, blocker), - ]); - - const blocking = { - id: genId(), - createdAt: new Date(), - blocker, - blockerId: blocker.id, - blockee, - blockeeId: blockee.id, - } as Blocking; - - await Blockings.insert(blocking); - - if (Users.isLocalUser(blocker) && Users.isRemoteUser(blockee)) { - const content = renderActivity(renderBlock(blocking)); - deliver(blocker, content, blockee.inbox); - } -} - -async function cancelRequest(follower: User, followee: User) { - const request = await FollowRequests.findOneBy({ - followeeId: followee.id, - followerId: follower.id, - }); - - if (request == null) { - return; - } - - await FollowRequests.delete({ - followeeId: followee.id, - followerId: follower.id, - }); - - if (Users.isLocalUser(followee)) { - Users.pack(followee, followee, { - detail: true, - }).then((packed) => publishMainStream(followee.id, "meUpdated", packed)); - } - - if (Users.isLocalUser(follower)) { - Users.pack(followee, follower, { - detail: true, - }).then(async (packed) => { - publishUserEvent(follower.id, "unfollow", packed); - publishMainStream(follower.id, "unfollow", packed); - - const webhooks = (await getActiveWebhooks()).filter( - (x) => x.userId === follower.id && x.on.includes("unfollow"), - ); - for (const webhook of webhooks) { - webhookDeliver(webhook, "unfollow", { - user: packed, - }); - } - }); - } - - // リモートにフォローリクエストをしていたらUndoFollow送信 - if (Users.isLocalUser(follower) && Users.isRemoteUser(followee)) { - const content = renderActivity( - renderUndo(renderFollow(follower, followee), follower), - ); - deliver(follower, content, followee.inbox); - } - - // リモートからフォローリクエストを受けていたらReject送信 - if (Users.isRemoteUser(follower) && Users.isLocalUser(followee)) { - const content = renderActivity( - renderReject( - renderFollow(follower, followee, request.requestId!), - followee, - ), - ); - deliver(followee, content, follower.inbox); - } -} - -async function unFollow(follower: User, followee: User) { - const following = await Followings.findOneBy({ - followerId: follower.id, - followeeId: followee.id, - }); - - if (following == null) { - return; - } - - await Promise.all([ - Followings.delete(following.id), - Users.decrement({ id: follower.id }, "followingCount", 1), - Users.decrement({ id: followee.id }, "followersCount", 1), - perUserFollowingChart.update(follower, followee, false), - ]); - - // Publish unfollow event - if (Users.isLocalUser(follower)) { - Users.pack(followee, follower, { - detail: true, - }).then(async (packed) => { - publishUserEvent(follower.id, "unfollow", packed); - publishMainStream(follower.id, "unfollow", packed); - - const webhooks = (await getActiveWebhooks()).filter( - (x) => x.userId === follower.id && x.on.includes("unfollow"), - ); - for (const webhook of webhooks) { - webhookDeliver(webhook, "unfollow", { - user: packed, - }); - } - }); - } - - // リモートにフォローをしていたらUndoFollow送信 - if (Users.isLocalUser(follower) && Users.isRemoteUser(followee)) { - const content = renderActivity( - renderUndo(renderFollow(follower, followee), follower), - ); - deliver(follower, content, followee.inbox); - } -} - -async function removeFromList(listOwner: User, user: User) { - const userLists = await UserLists.findBy({ - userId: listOwner.id, - }); - - for (const userList of userLists) { - await UserListJoinings.delete({ - userListId: userList.id, - userId: user.id, - }); - } -} diff --git a/packages/backend/src/services/blocking/delete.ts b/packages/backend/src/services/blocking/delete.ts deleted file mode 100644 index 67f1e76f0e..0000000000 --- a/packages/backend/src/services/blocking/delete.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import { renderBlock } from "@/remote/activitypub/renderer/block.js"; -import renderUndo from "@/remote/activitypub/renderer/undo.js"; -import { deliver } from "@/queue/index.js"; -import Logger from "../logger.js"; -import type { CacheableUser } from "@/models/entities/user.js"; -import { User } from "@/models/entities/user.js"; -import { Blockings, Users } from "@/models/index.js"; - -const logger = new Logger("blocking/delete"); - -export default async function (blocker: CacheableUser, blockee: CacheableUser) { - const blocking = await Blockings.findOneBy({ - blockerId: blocker.id, - blockeeId: blockee.id, - }); - - if (blocking == null) { - logger.warn( - "ブロック解除がリクエストされましたがブロックしていませんでした", - ); - return; - } - - // Since we already have the blocker and blockee, we do not need to fetch - // them in the query above and can just manually insert them here. - blocking.blocker = blocker; - blocking.blockee = blockee; - - Blockings.delete(blocking.id); - - // deliver if remote bloking - if (Users.isLocalUser(blocker) && Users.isRemoteUser(blockee)) { - const content = renderActivity(renderUndo(renderBlock(blocking), blocker)); - deliver(blocker, content, blockee.inbox); - } -} diff --git a/packages/backend/src/services/chart/charts/active-users.ts b/packages/backend/src/services/chart/charts/active-users.ts deleted file mode 100644 index 7a0c45cfaf..0000000000 --- a/packages/backend/src/services/chart/charts/active-users.ts +++ /dev/null @@ -1,59 +0,0 @@ -import type { KVs } from "../core.js"; -import Chart from "../core.js"; -import type { User } from "@/models/entities/user.js"; -import { Users } from "@/models/index.js"; -import { name, schema } from "./entities/active-users.js"; - -const week = 1000 * 60 * 60 * 24 * 7; -const month = 1000 * 60 * 60 * 24 * 30; -const year = 1000 * 60 * 60 * 24 * 365; - -/** - * アクティブユーザーに関するチャート - */ - -export default class ActiveUsersChart extends Chart<typeof schema> { - constructor() { - super(name, schema); - } - - protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - protected async tickMinor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - public async read(user: { - id: User["id"]; - host: null; - createdAt: User["createdAt"]; - }): Promise<void> { - await this.commit({ - read: [user.id], - registeredWithinWeek: - Date.now() - user.createdAt.getTime() < week ? [user.id] : [], - registeredWithinMonth: - Date.now() - user.createdAt.getTime() < month ? [user.id] : [], - registeredWithinYear: - Date.now() - user.createdAt.getTime() < year ? [user.id] : [], - registeredOutsideWeek: - Date.now() - user.createdAt.getTime() > week ? [user.id] : [], - registeredOutsideMonth: - Date.now() - user.createdAt.getTime() > month ? [user.id] : [], - registeredOutsideYear: - Date.now() - user.createdAt.getTime() > year ? [user.id] : [], - }); - } - - public async write(user: { - id: User["id"]; - host: null; - createdAt: User["createdAt"]; - }): Promise<void> { - await this.commit({ - write: [user.id], - }); - } -} diff --git a/packages/backend/src/services/chart/charts/ap-request.ts b/packages/backend/src/services/chart/charts/ap-request.ts deleted file mode 100644 index 6e56be0b36..0000000000 --- a/packages/backend/src/services/chart/charts/ap-request.ts +++ /dev/null @@ -1,39 +0,0 @@ -import type { KVs } from "../core.js"; -import Chart from "../core.js"; -import { name, schema } from "./entities/ap-request.js"; - -/** - * Chart about ActivityPub requests - */ - -export default class ApRequestChart extends Chart<typeof schema> { - constructor() { - super(name, schema); - } - - protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - protected async tickMinor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - public async deliverSucc(): Promise<void> { - await this.commit({ - deliverSucceeded: 1, - }); - } - - public async deliverFail(): Promise<void> { - await this.commit({ - deliverFailed: 1, - }); - } - - public async inbox(): Promise<void> { - await this.commit({ - inboxReceived: 1, - }); - } -} diff --git a/packages/backend/src/services/chart/charts/drive.ts b/packages/backend/src/services/chart/charts/drive.ts deleted file mode 100644 index 9793ff79dc..0000000000 --- a/packages/backend/src/services/chart/charts/drive.ts +++ /dev/null @@ -1,43 +0,0 @@ -import type { KVs } from "../core.js"; -import Chart from "../core.js"; -import { DriveFiles } from "@/models/index.js"; -import { Not, IsNull } from "typeorm"; -import type { DriveFile } from "@/models/entities/drive-file.js"; -import { name, schema } from "./entities/drive.js"; - -/** - * ドライブに関するチャート - */ - -export default class DriveChart extends Chart<typeof schema> { - constructor() { - super(name, schema); - } - - protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - protected async tickMinor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - public async update(file: DriveFile, isAdditional: boolean): Promise<void> { - const fileSizeKb = file.size / 1000; - await this.commit( - file.userHost === null - ? { - "local.incCount": isAdditional ? 1 : 0, - "local.incSize": isAdditional ? fileSizeKb : 0, - "local.decCount": isAdditional ? 0 : 1, - "local.decSize": isAdditional ? 0 : fileSizeKb, - } - : { - "remote.incCount": isAdditional ? 1 : 0, - "remote.incSize": isAdditional ? fileSizeKb : 0, - "remote.decCount": isAdditional ? 0 : 1, - "remote.decSize": isAdditional ? 0 : fileSizeKb, - }, - ); - } -} diff --git a/packages/backend/src/services/chart/charts/entities/active-users.ts b/packages/backend/src/services/chart/charts/entities/active-users.ts deleted file mode 100644 index 4e5fa37a27..0000000000 --- a/packages/backend/src/services/chart/charts/entities/active-users.ts +++ /dev/null @@ -1,17 +0,0 @@ -import Chart from "../../core.js"; - -export const name = "activeUsers"; - -export const schema = { - readWrite: { intersection: ["read", "write"], range: "small" }, - read: { uniqueIncrement: true, range: "small" }, - write: { uniqueIncrement: true, range: "small" }, - registeredWithinWeek: { uniqueIncrement: true, range: "small" }, - registeredWithinMonth: { uniqueIncrement: true, range: "small" }, - registeredWithinYear: { uniqueIncrement: true, range: "small" }, - registeredOutsideWeek: { uniqueIncrement: true, range: "small" }, - registeredOutsideMonth: { uniqueIncrement: true, range: "small" }, - registeredOutsideYear: { uniqueIncrement: true, range: "small" }, -} as const; - -export const entity = Chart.schemaToEntity(name, schema); diff --git a/packages/backend/src/services/chart/charts/entities/ap-request.ts b/packages/backend/src/services/chart/charts/entities/ap-request.ts deleted file mode 100644 index eb02201742..0000000000 --- a/packages/backend/src/services/chart/charts/entities/ap-request.ts +++ /dev/null @@ -1,11 +0,0 @@ -import Chart from "../../core.js"; - -export const name = "apRequest"; - -export const schema = { - deliverFailed: {}, - deliverSucceeded: {}, - inboxReceived: {}, -} as const; - -export const entity = Chart.schemaToEntity(name, schema); diff --git a/packages/backend/src/services/chart/charts/entities/drive.ts b/packages/backend/src/services/chart/charts/entities/drive.ts deleted file mode 100644 index 0280ec655f..0000000000 --- a/packages/backend/src/services/chart/charts/entities/drive.ts +++ /dev/null @@ -1,16 +0,0 @@ -import Chart from "../../core.js"; - -export const name = "drive"; - -export const schema = { - "local.incCount": {}, - "local.incSize": {}, // in kilobyte - "local.decCount": {}, - "local.decSize": {}, // in kilobyte - "remote.incCount": {}, - "remote.incSize": {}, // in kilobyte - "remote.decCount": {}, - "remote.decSize": {}, // in kilobyte -} as const; - -export const entity = Chart.schemaToEntity(name, schema); diff --git a/packages/backend/src/services/chart/charts/entities/federation.ts b/packages/backend/src/services/chart/charts/entities/federation.ts deleted file mode 100644 index b77e020961..0000000000 --- a/packages/backend/src/services/chart/charts/entities/federation.ts +++ /dev/null @@ -1,16 +0,0 @@ -import Chart from "../../core.js"; - -export const name = "federation"; - -export const schema = { - deliveredInstances: { uniqueIncrement: true, range: "small" }, - inboxInstances: { uniqueIncrement: true, range: "small" }, - stalled: { uniqueIncrement: true, range: "small" }, - sub: { accumulate: true, range: "small" }, - pub: { accumulate: true, range: "small" }, - pubsub: { accumulate: true, range: "small" }, - subActive: { accumulate: true, range: "small" }, - pubActive: { accumulate: true, range: "small" }, -} as const; - -export const entity = Chart.schemaToEntity(name, schema); diff --git a/packages/backend/src/services/chart/charts/entities/hashtag.ts b/packages/backend/src/services/chart/charts/entities/hashtag.ts deleted file mode 100644 index 77964b4ca1..0000000000 --- a/packages/backend/src/services/chart/charts/entities/hashtag.ts +++ /dev/null @@ -1,10 +0,0 @@ -import Chart from "../../core.js"; - -export const name = "hashtag"; - -export const schema = { - "local.users": { uniqueIncrement: true }, - "remote.users": { uniqueIncrement: true }, -} as const; - -export const entity = Chart.schemaToEntity(name, schema, true); diff --git a/packages/backend/src/services/chart/charts/entities/instance.ts b/packages/backend/src/services/chart/charts/entities/instance.ts deleted file mode 100644 index a75dea475b..0000000000 --- a/packages/backend/src/services/chart/charts/entities/instance.ts +++ /dev/null @@ -1,32 +0,0 @@ -import Chart from "../../core.js"; - -export const name = "instance"; - -export const schema = { - "requests.failed": { range: "small" }, - "requests.succeeded": { range: "small" }, - "requests.received": { range: "small" }, - "notes.total": { accumulate: true }, - "notes.inc": {}, - "notes.dec": {}, - "notes.diffs.normal": {}, - "notes.diffs.reply": {}, - "notes.diffs.renote": {}, - "notes.diffs.withFile": {}, - "users.total": { accumulate: true }, - "users.inc": { range: "small" }, - "users.dec": { range: "small" }, - "following.total": { accumulate: true }, - "following.inc": { range: "small" }, - "following.dec": { range: "small" }, - "followers.total": { accumulate: true }, - "followers.inc": { range: "small" }, - "followers.dec": { range: "small" }, - "drive.totalFiles": { accumulate: true }, - "drive.incFiles": {}, - "drive.decFiles": {}, - "drive.incUsage": {}, // in kilobyte - "drive.decUsage": {}, // in kilobyte -} as const; - -export const entity = Chart.schemaToEntity(name, schema, true); diff --git a/packages/backend/src/services/chart/charts/entities/notes.ts b/packages/backend/src/services/chart/charts/entities/notes.ts deleted file mode 100644 index 04e75a2f29..0000000000 --- a/packages/backend/src/services/chart/charts/entities/notes.ts +++ /dev/null @@ -1,22 +0,0 @@ -import Chart from "../../core.js"; - -export const name = "notes"; - -export const schema = { - "local.total": { accumulate: true }, - "local.inc": {}, - "local.dec": {}, - "local.diffs.normal": {}, - "local.diffs.reply": {}, - "local.diffs.renote": {}, - "local.diffs.withFile": {}, - "remote.total": { accumulate: true }, - "remote.inc": {}, - "remote.dec": {}, - "remote.diffs.normal": {}, - "remote.diffs.reply": {}, - "remote.diffs.renote": {}, - "remote.diffs.withFile": {}, -} as const; - -export const entity = Chart.schemaToEntity(name, schema); diff --git a/packages/backend/src/services/chart/charts/entities/per-user-drive.ts b/packages/backend/src/services/chart/charts/entities/per-user-drive.ts deleted file mode 100644 index d9dcd3d35e..0000000000 --- a/packages/backend/src/services/chart/charts/entities/per-user-drive.ts +++ /dev/null @@ -1,14 +0,0 @@ -import Chart from "../../core.js"; - -export const name = "perUserDrive"; - -export const schema = { - totalCount: { accumulate: true }, - totalSize: { accumulate: true }, // in kilobyte - incCount: { range: "small" }, - incSize: {}, // in kilobyte - decCount: { range: "small" }, - decSize: {}, // in kilobyte -} as const; - -export const entity = Chart.schemaToEntity(name, schema, true); diff --git a/packages/backend/src/services/chart/charts/entities/per-user-following.ts b/packages/backend/src/services/chart/charts/entities/per-user-following.ts deleted file mode 100644 index 3cbeec1114..0000000000 --- a/packages/backend/src/services/chart/charts/entities/per-user-following.ts +++ /dev/null @@ -1,20 +0,0 @@ -import Chart from "../../core.js"; - -export const name = "perUserFollowing"; - -export const schema = { - "local.followings.total": { accumulate: true }, - "local.followings.inc": { range: "small" }, - "local.followings.dec": { range: "small" }, - "local.followers.total": { accumulate: true }, - "local.followers.inc": { range: "small" }, - "local.followers.dec": { range: "small" }, - "remote.followings.total": { accumulate: true }, - "remote.followings.inc": { range: "small" }, - "remote.followings.dec": { range: "small" }, - "remote.followers.total": { accumulate: true }, - "remote.followers.inc": { range: "small" }, - "remote.followers.dec": { range: "small" }, -} as const; - -export const entity = Chart.schemaToEntity(name, schema, true); diff --git a/packages/backend/src/services/chart/charts/entities/per-user-notes.ts b/packages/backend/src/services/chart/charts/entities/per-user-notes.ts deleted file mode 100644 index 30c22e2f46..0000000000 --- a/packages/backend/src/services/chart/charts/entities/per-user-notes.ts +++ /dev/null @@ -1,15 +0,0 @@ -import Chart from "../../core.js"; - -export const name = "perUserNotes"; - -export const schema = { - total: { accumulate: true }, - inc: { range: "small" }, - dec: { range: "small" }, - "diffs.normal": { range: "small" }, - "diffs.reply": { range: "small" }, - "diffs.renote": { range: "small" }, - "diffs.withFile": { range: "small" }, -} as const; - -export const entity = Chart.schemaToEntity(name, schema, true); diff --git a/packages/backend/src/services/chart/charts/entities/per-user-reactions.ts b/packages/backend/src/services/chart/charts/entities/per-user-reactions.ts deleted file mode 100644 index f281531c0c..0000000000 --- a/packages/backend/src/services/chart/charts/entities/per-user-reactions.ts +++ /dev/null @@ -1,10 +0,0 @@ -import Chart from "../../core.js"; - -export const name = "perUserReaction"; - -export const schema = { - "local.count": { range: "small" }, - "remote.count": { range: "small" }, -} as const; - -export const entity = Chart.schemaToEntity(name, schema, true); diff --git a/packages/backend/src/services/chart/charts/entities/test-grouped.ts b/packages/backend/src/services/chart/charts/entities/test-grouped.ts deleted file mode 100644 index 428f2bb36c..0000000000 --- a/packages/backend/src/services/chart/charts/entities/test-grouped.ts +++ /dev/null @@ -1,11 +0,0 @@ -import Chart from "../../core.js"; - -export const name = "testGrouped"; - -export const schema = { - "foo.total": { accumulate: true }, - "foo.inc": {}, - "foo.dec": {}, -} as const; - -export const entity = Chart.schemaToEntity(name, schema, true); diff --git a/packages/backend/src/services/chart/charts/entities/test-intersection.ts b/packages/backend/src/services/chart/charts/entities/test-intersection.ts deleted file mode 100644 index 30d8753d7a..0000000000 --- a/packages/backend/src/services/chart/charts/entities/test-intersection.ts +++ /dev/null @@ -1,11 +0,0 @@ -import Chart from "../../core.js"; - -export const name = "testIntersection"; - -export const schema = { - a: { uniqueIncrement: true }, - b: { uniqueIncrement: true }, - aAndB: { intersection: ["a", "b"] }, -} as const; - -export const entity = Chart.schemaToEntity(name, schema); diff --git a/packages/backend/src/services/chart/charts/entities/test-unique.ts b/packages/backend/src/services/chart/charts/entities/test-unique.ts deleted file mode 100644 index 03b8a7653e..0000000000 --- a/packages/backend/src/services/chart/charts/entities/test-unique.ts +++ /dev/null @@ -1,9 +0,0 @@ -import Chart from "../../core.js"; - -export const name = "testUnique"; - -export const schema = { - foo: { uniqueIncrement: true }, -} as const; - -export const entity = Chart.schemaToEntity(name, schema); diff --git a/packages/backend/src/services/chart/charts/entities/test.ts b/packages/backend/src/services/chart/charts/entities/test.ts deleted file mode 100644 index a11d53e32e..0000000000 --- a/packages/backend/src/services/chart/charts/entities/test.ts +++ /dev/null @@ -1,11 +0,0 @@ -import Chart from "../../core.js"; - -export const name = "test"; - -export const schema = { - "foo.total": { accumulate: true }, - "foo.inc": {}, - "foo.dec": {}, -} as const; - -export const entity = Chart.schemaToEntity(name, schema); diff --git a/packages/backend/src/services/chart/charts/entities/users.ts b/packages/backend/src/services/chart/charts/entities/users.ts deleted file mode 100644 index a9544d77b1..0000000000 --- a/packages/backend/src/services/chart/charts/entities/users.ts +++ /dev/null @@ -1,14 +0,0 @@ -import Chart from "../../core.js"; - -export const name = "users"; - -export const schema = { - "local.total": { accumulate: true }, - "local.inc": { range: "small" }, - "local.dec": { range: "small" }, - "remote.total": { accumulate: true }, - "remote.inc": { range: "small" }, - "remote.dec": { range: "small" }, -} as const; - -export const entity = Chart.schemaToEntity(name, schema); diff --git a/packages/backend/src/services/chart/charts/federation.ts b/packages/backend/src/services/chart/charts/federation.ts deleted file mode 100644 index 1a03d574df..0000000000 --- a/packages/backend/src/services/chart/charts/federation.ts +++ /dev/null @@ -1,142 +0,0 @@ -import type { KVs } from "../core.js"; -import Chart from "../core.js"; -import { Followings, Instances } from "@/models/index.js"; -import { name, schema } from "./entities/federation.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; - -/** - * フェデレーションに関するチャート - */ - -export default class FederationChart extends Chart<typeof schema> { - constructor() { - super(name, schema); - } - - protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - protected async tickMinor(): Promise<Partial<KVs<typeof schema>>> { - const meta = await fetchMeta(); - - const suspendedInstancesQuery = Instances.createQueryBuilder("instance") - .select("instance.host") - .where("instance.isSuspended = true"); - - const pubsubSubQuery = Followings.createQueryBuilder("f") - .select("f.followerHost") - .where("f.followerHost IS NOT NULL"); - - const subInstancesQuery = Followings.createQueryBuilder("f") - .select("f.followeeHost") - .where("f.followeeHost IS NOT NULL"); - - const pubInstancesQuery = Followings.createQueryBuilder("f") - .select("f.followerHost") - .where("f.followerHost IS NOT NULL"); - - const [sub, pub, pubsub, subActive, pubActive] = await Promise.all([ - Followings.createQueryBuilder("following") - .select("COUNT(DISTINCT following.followeeHost)") - .where("following.followeeHost IS NOT NULL") - .andWhere( - meta.blockedHosts.length === 0 - ? "1=1" - : "following.followeeHost NOT IN (:...blocked)", - { blocked: meta.blockedHosts }, - ) - .andWhere( - `following.followeeHost NOT IN (${suspendedInstancesQuery.getQuery()})`, - ) - .getRawOne() - .then((x) => parseInt(x.count, 10)), - Followings.createQueryBuilder("following") - .select("COUNT(DISTINCT following.followerHost)") - .where("following.followerHost IS NOT NULL") - .andWhere( - meta.blockedHosts.length === 0 - ? "1=1" - : "following.followerHost NOT IN (:...blocked)", - { blocked: meta.blockedHosts }, - ) - .andWhere( - `following.followerHost NOT IN (${suspendedInstancesQuery.getQuery()})`, - ) - .getRawOne() - .then((x) => parseInt(x.count, 10)), - Followings.createQueryBuilder("following") - .select("COUNT(DISTINCT following.followeeHost)") - .where("following.followeeHost IS NOT NULL") - .andWhere( - meta.blockedHosts.length === 0 - ? "1=1" - : "following.followeeHost NOT IN (:...blocked)", - { blocked: meta.blockedHosts }, - ) - .andWhere( - `following.followeeHost NOT IN (${suspendedInstancesQuery.getQuery()})`, - ) - .andWhere(`following.followeeHost IN (${pubsubSubQuery.getQuery()})`) - .setParameters(pubsubSubQuery.getParameters()) - .getRawOne() - .then((x) => parseInt(x.count, 10)), - Instances.createQueryBuilder("instance") - .select("COUNT(instance.id)") - .where(`instance.host IN (${subInstancesQuery.getQuery()})`) - .andWhere( - meta.blockedHosts.length === 0 - ? "1=1" - : "instance.host NOT IN (:...blocked)", - { blocked: meta.blockedHosts }, - ) - .andWhere("instance.isSuspended = false") - .andWhere("instance.lastCommunicatedAt > :gt", { - gt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 30), - }) - .getRawOne() - .then((x) => parseInt(x.count, 10)), - Instances.createQueryBuilder("instance") - .select("COUNT(instance.id)") - .where(`instance.host IN (${pubInstancesQuery.getQuery()})`) - .andWhere( - meta.blockedHosts.length === 0 - ? "1=1" - : "instance.host NOT IN (:...blocked)", - { blocked: meta.blockedHosts }, - ) - .andWhere("instance.isSuspended = false") - .andWhere("instance.lastCommunicatedAt > :gt", { - gt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 30), - }) - .getRawOne() - .then((x) => parseInt(x.count, 10)), - ]); - - return { - sub: sub, - pub: pub, - pubsub: pubsub, - subActive: subActive, - pubActive: pubActive, - }; - } - - public async deliverd(host: string, succeeded: boolean): Promise<void> { - await this.commit( - succeeded - ? { - deliveredInstances: [host], - } - : { - stalled: [host], - }, - ); - } - - public async inbox(host: string): Promise<void> { - await this.commit({ - inboxInstances: [host], - }); - } -} diff --git a/packages/backend/src/services/chart/charts/hashtag.ts b/packages/backend/src/services/chart/charts/hashtag.ts deleted file mode 100644 index 0211df857f..0000000000 --- a/packages/backend/src/services/chart/charts/hashtag.ts +++ /dev/null @@ -1,36 +0,0 @@ -import type { KVs } from "../core.js"; -import Chart from "../core.js"; -import type { User } from "@/models/entities/user.js"; -import { Users } from "@/models/index.js"; -import { name, schema } from "./entities/hashtag.js"; - -/** - * ハッシュタグに関するチャート - */ - -export default class HashtagChart extends Chart<typeof schema> { - constructor() { - super(name, schema, true); - } - - protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - protected async tickMinor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - public async update( - hashtag: string, - user: { id: User["id"]; host: User["host"] }, - ): Promise<void> { - await this.commit( - { - "local.users": Users.isLocalUser(user) ? [user.id] : [], - "remote.users": Users.isLocalUser(user) ? [] : [user.id], - }, - hashtag, - ); - } -} diff --git a/packages/backend/src/services/chart/charts/instance.ts b/packages/backend/src/services/chart/charts/instance.ts deleted file mode 100644 index d6e3483d8e..0000000000 --- a/packages/backend/src/services/chart/charts/instance.ts +++ /dev/null @@ -1,142 +0,0 @@ -import type { KVs } from "../core.js"; -import Chart from "../core.js"; -import { DriveFiles, Followings, Users, Notes } from "@/models/index.js"; -import type { DriveFile } from "@/models/entities/drive-file.js"; -import type { Note } from "@/models/entities/note.js"; -import { toPuny } from "@/misc/convert-host.js"; -import { name, schema } from "./entities/instance.js"; - -/** - * インスタンスごとのチャート - */ - -export default class InstanceChart extends Chart<typeof schema> { - constructor() { - super(name, schema, true); - } - - protected async tickMajor( - group: string, - ): Promise<Partial<KVs<typeof schema>>> { - const [notesCount, usersCount, followingCount, followersCount, driveFiles] = - await Promise.all([ - Notes.countBy({ userHost: group }), - Users.countBy({ host: group }), - Followings.countBy({ followerHost: group }), - Followings.countBy({ followeeHost: group }), - DriveFiles.countBy({ userHost: group }), - ]); - - return { - "notes.total": notesCount, - "users.total": usersCount, - "following.total": followingCount, - "followers.total": followersCount, - "drive.totalFiles": driveFiles, - }; - } - - protected async tickMinor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - public async requestReceived(host: string): Promise<void> { - await this.commit( - { - "requests.received": 1, - }, - toPuny(host), - ); - } - - public async requestSent(host: string, isSucceeded: boolean): Promise<void> { - await this.commit( - { - "requests.succeeded": isSucceeded ? 1 : 0, - "requests.failed": isSucceeded ? 0 : 1, - }, - toPuny(host), - ); - } - - public async newUser(host: string): Promise<void> { - await this.commit( - { - "users.total": 1, - "users.inc": 1, - }, - toPuny(host), - ); - } - - public async updateNote( - host: string, - note: Note, - isAdditional: boolean, - ): Promise<void> { - await this.commit( - { - "notes.total": isAdditional ? 1 : -1, - "notes.inc": isAdditional ? 1 : 0, - "notes.dec": isAdditional ? 0 : 1, - "notes.diffs.normal": - note.replyId == null && note.renoteId == null - ? isAdditional - ? 1 - : -1 - : 0, - "notes.diffs.renote": - note.renoteId != null ? (isAdditional ? 1 : -1) : 0, - "notes.diffs.reply": note.replyId != null ? (isAdditional ? 1 : -1) : 0, - "notes.diffs.withFile": - note.fileIds.length > 0 ? (isAdditional ? 1 : -1) : 0, - }, - toPuny(host), - ); - } - - public async updateFollowing( - host: string, - isAdditional: boolean, - ): Promise<void> { - await this.commit( - { - "following.total": isAdditional ? 1 : -1, - "following.inc": isAdditional ? 1 : 0, - "following.dec": isAdditional ? 0 : 1, - }, - toPuny(host), - ); - } - - public async updateFollowers( - host: string, - isAdditional: boolean, - ): Promise<void> { - await this.commit( - { - "followers.total": isAdditional ? 1 : -1, - "followers.inc": isAdditional ? 1 : 0, - "followers.dec": isAdditional ? 0 : 1, - }, - toPuny(host), - ); - } - - public async updateDrive( - file: DriveFile, - isAdditional: boolean, - ): Promise<void> { - const fileSizeKb = file.size / 1000; - await this.commit( - { - "drive.totalFiles": isAdditional ? 1 : -1, - "drive.incFiles": isAdditional ? 1 : 0, - "drive.incUsage": isAdditional ? fileSizeKb : 0, - "drive.decFiles": isAdditional ? 1 : 0, - "drive.decUsage": isAdditional ? fileSizeKb : 0, - }, - file.userHost, - ); - } -} diff --git a/packages/backend/src/services/chart/charts/notes.ts b/packages/backend/src/services/chart/charts/notes.ts deleted file mode 100644 index 9ec347b470..0000000000 --- a/packages/backend/src/services/chart/charts/notes.ts +++ /dev/null @@ -1,54 +0,0 @@ -import type { KVs } from "../core.js"; -import Chart from "../core.js"; -import { Notes } from "@/models/index.js"; -import { Not, IsNull } from "typeorm"; -import type { Note } from "@/models/entities/note.js"; -import { name, schema } from "./entities/notes.js"; - -/** - * ノートに関するチャート - */ - -export default class NotesChart extends Chart<typeof schema> { - constructor() { - super(name, schema); - } - - protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> { - const [localCount, remoteCount] = await Promise.all([ - Notes.countBy({ userHost: IsNull() }), - Notes.countBy({ userHost: Not(IsNull()) }), - ]); - - return { - "local.total": localCount, - "remote.total": remoteCount, - }; - } - - protected async tickMinor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - public async update(note: Note, isAdditional: boolean): Promise<void> { - const prefix = note.userHost === null ? "local" : "remote"; - - await this.commit({ - [`${prefix}.total`]: isAdditional ? 1 : -1, - [`${prefix}.inc`]: isAdditional ? 1 : 0, - [`${prefix}.dec`]: isAdditional ? 0 : 1, - [`${prefix}.diffs.normal`]: - note.replyId == null && note.renoteId == null - ? isAdditional - ? 1 - : -1 - : 0, - [`${prefix}.diffs.renote`]: - note.renoteId != null ? (isAdditional ? 1 : -1) : 0, - [`${prefix}.diffs.reply`]: - note.replyId != null ? (isAdditional ? 1 : -1) : 0, - [`${prefix}.diffs.withFile`]: - note.fileIds.length > 0 ? (isAdditional ? 1 : -1) : 0, - }); - } -} diff --git a/packages/backend/src/services/chart/charts/per-user-drive.ts b/packages/backend/src/services/chart/charts/per-user-drive.ts deleted file mode 100644 index 18589bb84a..0000000000 --- a/packages/backend/src/services/chart/charts/per-user-drive.ts +++ /dev/null @@ -1,48 +0,0 @@ -import type { KVs } from "../core.js"; -import Chart from "../core.js"; -import { DriveFiles } from "@/models/index.js"; -import type { DriveFile } from "@/models/entities/drive-file.js"; -import { name, schema } from "./entities/per-user-drive.js"; - -/** - * ユーザーごとのドライブに関するチャート - */ - -export default class PerUserDriveChart extends Chart<typeof schema> { - constructor() { - super(name, schema, true); - } - - protected async tickMajor( - group: string, - ): Promise<Partial<KVs<typeof schema>>> { - const [count, size] = await Promise.all([ - DriveFiles.countBy({ userId: group }), - DriveFiles.calcDriveUsageOf(group), - ]); - - return { - totalCount: count, - totalSize: size, - }; - } - - protected async tickMinor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - public async update(file: DriveFile, isAdditional: boolean): Promise<void> { - const fileSizeKb = file.size / 1000; - await this.commit( - { - totalCount: isAdditional ? 1 : -1, - totalSize: isAdditional ? fileSizeKb : -fileSizeKb, - incCount: isAdditional ? 1 : 0, - incSize: isAdditional ? fileSizeKb : 0, - decCount: isAdditional ? 0 : 1, - decSize: isAdditional ? 0 : fileSizeKb, - }, - file.userId, - ); - } -} diff --git a/packages/backend/src/services/chart/charts/per-user-following.ts b/packages/backend/src/services/chart/charts/per-user-following.ts deleted file mode 100644 index 3e8b576f20..0000000000 --- a/packages/backend/src/services/chart/charts/per-user-following.ts +++ /dev/null @@ -1,69 +0,0 @@ -import type { KVs } from "../core.js"; -import Chart from "../core.js"; -import { Followings, Users } from "@/models/index.js"; -import { Not, IsNull } from "typeorm"; -import type { User } from "@/models/entities/user.js"; -import { name, schema } from "./entities/per-user-following.js"; - -/** - * ユーザーごとのフォローに関するチャート - */ - -export default class PerUserFollowingChart extends Chart<typeof schema> { - constructor() { - super(name, schema, true); - } - - protected async tickMajor( - group: string, - ): Promise<Partial<KVs<typeof schema>>> { - const [ - localFollowingsCount, - localFollowersCount, - remoteFollowingsCount, - remoteFollowersCount, - ] = await Promise.all([ - Followings.countBy({ followerId: group, followeeHost: IsNull() }), - Followings.countBy({ followeeId: group, followerHost: IsNull() }), - Followings.countBy({ followerId: group, followeeHost: Not(IsNull()) }), - Followings.countBy({ followeeId: group, followerHost: Not(IsNull()) }), - ]); - - return { - "local.followings.total": localFollowingsCount, - "local.followers.total": localFollowersCount, - "remote.followings.total": remoteFollowingsCount, - "remote.followers.total": remoteFollowersCount, - }; - } - - protected async tickMinor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - public async update( - follower: { id: User["id"]; host: User["host"] }, - followee: { id: User["id"]; host: User["host"] }, - isFollow: boolean, - ): Promise<void> { - const prefixFollower = Users.isLocalUser(follower) ? "local" : "remote"; - const prefixFollowee = Users.isLocalUser(followee) ? "local" : "remote"; - - this.commit( - { - [`${prefixFollower}.followings.total`]: isFollow ? 1 : -1, - [`${prefixFollower}.followings.inc`]: isFollow ? 1 : 0, - [`${prefixFollower}.followings.dec`]: isFollow ? 0 : 1, - }, - follower.id, - ); - this.commit( - { - [`${prefixFollowee}.followers.total`]: isFollow ? 1 : -1, - [`${prefixFollowee}.followers.inc`]: isFollow ? 1 : 0, - [`${prefixFollowee}.followers.dec`]: isFollow ? 0 : 1, - }, - followee.id, - ); - } -} diff --git a/packages/backend/src/services/chart/charts/per-user-notes.ts b/packages/backend/src/services/chart/charts/per-user-notes.ts deleted file mode 100644 index d0190cefd0..0000000000 --- a/packages/backend/src/services/chart/charts/per-user-notes.ts +++ /dev/null @@ -1,54 +0,0 @@ -import type { KVs } from "../core.js"; -import Chart from "../core.js"; -import type { User } from "@/models/entities/user.js"; -import { Notes } from "@/models/index.js"; -import type { Note } from "@/models/entities/note.js"; -import { name, schema } from "./entities/per-user-notes.js"; - -/** - * ユーザーごとのノートに関するチャート - */ - -export default class PerUserNotesChart extends Chart<typeof schema> { - constructor() { - super(name, schema, true); - } - - protected async tickMajor( - group: string, - ): Promise<Partial<KVs<typeof schema>>> { - const [count] = await Promise.all([Notes.countBy({ userId: group })]); - - return { - total: count, - }; - } - - protected async tickMinor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - public async update( - user: { id: User["id"] }, - note: Note, - isAdditional: boolean, - ): Promise<void> { - await this.commit( - { - total: isAdditional ? 1 : -1, - inc: isAdditional ? 1 : 0, - dec: isAdditional ? 0 : 1, - "diffs.normal": - note.replyId == null && note.renoteId == null - ? isAdditional - ? 1 - : -1 - : 0, - "diffs.renote": note.renoteId != null ? (isAdditional ? 1 : -1) : 0, - "diffs.reply": note.replyId != null ? (isAdditional ? 1 : -1) : 0, - "diffs.withFile": note.fileIds.length > 0 ? (isAdditional ? 1 : -1) : 0, - }, - user.id, - ); - } -} diff --git a/packages/backend/src/services/chart/charts/per-user-reactions.ts b/packages/backend/src/services/chart/charts/per-user-reactions.ts deleted file mode 100644 index 75def3de04..0000000000 --- a/packages/backend/src/services/chart/charts/per-user-reactions.ts +++ /dev/null @@ -1,39 +0,0 @@ -import type { KVs } from "../core.js"; -import Chart from "../core.js"; -import type { User } from "@/models/entities/user.js"; -import type { Note } from "@/models/entities/note.js"; -import { Users } from "@/models/index.js"; -import { name, schema } from "./entities/per-user-reactions.js"; - -/** - * ユーザーごとのリアクションに関するチャート - */ - -export default class PerUserReactionsChart extends Chart<typeof schema> { - constructor() { - super(name, schema, true); - } - - protected async tickMajor( - group: string, - ): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - protected async tickMinor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - public async update( - user: { id: User["id"]; host: User["host"] }, - note: Note, - ): Promise<void> { - const prefix = Users.isLocalUser(user) ? "local" : "remote"; - this.commit( - { - [`${prefix}.count`]: 1, - }, - note.userId, - ); - } -} diff --git a/packages/backend/src/services/chart/charts/test-grouped.ts b/packages/backend/src/services/chart/charts/test-grouped.ts deleted file mode 100644 index 6520099fe6..0000000000 --- a/packages/backend/src/services/chart/charts/test-grouped.ts +++ /dev/null @@ -1,41 +0,0 @@ -import type { KVs } from "../core.js"; -import Chart from "../core.js"; -import { name, schema } from "./entities/test-grouped.js"; - -/** - * For testing - */ - -export default class TestGroupedChart extends Chart<typeof schema> { - private total = {} as Record<string, number>; - - constructor() { - super(name, schema, true); - } - - protected async tickMajor( - group: string, - ): Promise<Partial<KVs<typeof schema>>> { - return { - "foo.total": this.total[group], - }; - } - - protected async tickMinor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - public async increment(group: string): Promise<void> { - if (this.total[group] == null) this.total[group] = 0; - - this.total[group]++; - - await this.commit( - { - "foo.total": 1, - "foo.inc": 1, - }, - group, - ); - } -} diff --git a/packages/backend/src/services/chart/charts/test-intersection.ts b/packages/backend/src/services/chart/charts/test-intersection.ts deleted file mode 100644 index 0fa973861f..0000000000 --- a/packages/backend/src/services/chart/charts/test-intersection.ts +++ /dev/null @@ -1,33 +0,0 @@ -import type { KVs } from "../core.js"; -import Chart from "../core.js"; -import { name, schema } from "./entities/test-intersection.js"; - -/** - * For testing - */ - -export default class TestIntersectionChart extends Chart<typeof schema> { - constructor() { - super(name, schema); - } - - protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - protected async tickMinor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - public async addA(key: string): Promise<void> { - await this.commit({ - a: [key], - }); - } - - public async addB(key: string): Promise<void> { - await this.commit({ - b: [key], - }); - } -} diff --git a/packages/backend/src/services/chart/charts/test-unique.ts b/packages/backend/src/services/chart/charts/test-unique.ts deleted file mode 100644 index 095021622c..0000000000 --- a/packages/backend/src/services/chart/charts/test-unique.ts +++ /dev/null @@ -1,27 +0,0 @@ -import type { KVs } from "../core.js"; -import Chart from "../core.js"; -import { name, schema } from "./entities/test-unique.js"; - -/** - * For testing - */ - -export default class TestUniqueChart extends Chart<typeof schema> { - constructor() { - super(name, schema); - } - - protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - protected async tickMinor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - public async uniqueIncrement(key: string): Promise<void> { - await this.commit({ - foo: [key], - }); - } -} diff --git a/packages/backend/src/services/chart/charts/test.ts b/packages/backend/src/services/chart/charts/test.ts deleted file mode 100644 index afdb3bf14e..0000000000 --- a/packages/backend/src/services/chart/charts/test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import type { KVs } from "../core.js"; -import Chart from "../core.js"; -import { name, schema } from "./entities/test.js"; - -/** - * For testing - */ - -export default class TestChart extends Chart<typeof schema> { - public total = 0; // publicにするのはテストのため - - constructor() { - super(name, schema); - } - - protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> { - return { - "foo.total": this.total, - }; - } - - protected async tickMinor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - public async increment(): Promise<void> { - this.total++; - - await this.commit({ - "foo.total": 1, - "foo.inc": 1, - }); - } - - public async decrement(): Promise<void> { - this.total--; - - await this.commit({ - "foo.total": -1, - "foo.dec": 1, - }); - } -} diff --git a/packages/backend/src/services/chart/charts/users.ts b/packages/backend/src/services/chart/charts/users.ts deleted file mode 100644 index 6fef9ecf7b..0000000000 --- a/packages/backend/src/services/chart/charts/users.ts +++ /dev/null @@ -1,45 +0,0 @@ -import type { KVs } from "../core.js"; -import Chart from "../core.js"; -import { Users } from "@/models/index.js"; -import { Not, IsNull } from "typeorm"; -import type { User } from "@/models/entities/user.js"; -import { name, schema } from "./entities/users.js"; - -/** - * ユーザー数に関するチャート - */ - -export default class UsersChart extends Chart<typeof schema> { - constructor() { - super(name, schema); - } - - protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> { - const [localCount, remoteCount] = await Promise.all([ - Users.countBy({ host: IsNull() }), - Users.countBy({ host: Not(IsNull()) }), - ]); - - return { - "local.total": localCount, - "remote.total": remoteCount, - }; - } - - protected async tickMinor(): Promise<Partial<KVs<typeof schema>>> { - return {}; - } - - public async update( - user: { id: User["id"]; host: User["host"] }, - isAdditional: boolean, - ): Promise<void> { - const prefix = Users.isLocalUser(user) ? "local" : "remote"; - - await this.commit({ - [`${prefix}.total`]: isAdditional ? 1 : -1, - [`${prefix}.inc`]: isAdditional ? 1 : 0, - [`${prefix}.dec`]: isAdditional ? 0 : 1, - }); - } -} diff --git a/packages/backend/src/services/chart/core.ts b/packages/backend/src/services/chart/core.ts deleted file mode 100644 index 36fe373269..0000000000 --- a/packages/backend/src/services/chart/core.ts +++ /dev/null @@ -1,922 +0,0 @@ -/** - * チャートエンジン - * - * Tests located in test/chart - */ - -import * as nestedProperty from "nested-property"; -import Logger from "../logger.js"; -import type { Repository } from "typeorm"; -import { EntitySchema, LessThan, Between } from "typeorm"; -import { - dateUTC, - isTimeSame, - isTimeBefore, - subtractTime, - addTime, -} from "@/prelude/time.js"; -import { getChartInsertLock } from "@/misc/app-lock.js"; -import { db } from "@/db/postgre.js"; -import promiseLimit from "promise-limit"; - -const logger = new Logger("chart", "white", process.env.NODE_ENV !== "test"); - -const columnPrefix = "___" as const; -const uniqueTempColumnPrefix = "unique_temp___" as const; -const columnDot = "_" as const; - -type Schema = Record< - string, - { - uniqueIncrement?: boolean; - - intersection?: string[] | ReadonlyArray<string>; - - range?: "big" | "small" | "medium"; - - // previousな値を引き継ぐかどうか - accumulate?: boolean; - } ->; - -type KeyToColumnName<T extends string> = T extends `${infer R1}.${infer R2}` - ? `${R1}${typeof columnDot}${KeyToColumnName<R2>}` - : T; - -type Columns<S extends Schema> = { - [K in - keyof S as `${typeof columnPrefix}${KeyToColumnName<string & K>}`]: number; -}; - -type TempColumnsForUnique<S extends Schema> = { - [K in - keyof S as `${typeof uniqueTempColumnPrefix}${KeyToColumnName< - string & K - >}`]: S[K]["uniqueIncrement"] extends true ? string[] : never; -}; - -type RawRecord<S extends Schema> = { - id: number; - - /** - * 集計のグループ - */ - group?: string | null; - - /** - * 集計日時のUnixタイムスタンプ(秒) - */ - date: number; -} & TempColumnsForUnique<S> & - Columns<S>; - -const camelToSnake = (str: string): string => { - return str.replace(/([A-Z])/g, (s) => `_${s.charAt(0).toLowerCase()}`); -}; - -const removeDuplicates = (array: any[]) => Array.from(new Set(array)); - -type Commit<S extends Schema> = { - [K in keyof S]?: S[K]["uniqueIncrement"] extends true ? string[] : number; -}; - -export type KVs<S extends Schema> = { - [K in keyof S]: number; -}; - -type ChartResult<T extends Schema> = { - [P in keyof T]: number[]; -}; - -type UnionToIntersection<T> = (T extends any ? (x: T) => any : never) extends ( - x: infer R, -) => any - ? R - : never; - -type UnflattenSingleton<K extends string, V> = K extends `${infer A}.${infer B}` - ? { - [_ in A]: UnflattenSingleton<B, V>; - } - : { - [_ in K]: V; - }; - -type Unflatten<T extends Record<string, any>> = UnionToIntersection< - { - [K in Extract<keyof T, string>]: UnflattenSingleton<K, T[K]>; - }[Extract<keyof T, string>] ->; - -type ToJsonSchema<S> = { - type: "object"; - properties: { - [K in keyof S]: S[K] extends number[] - ? { type: "array"; items: { type: "number" } } - : ToJsonSchema<S[K]>; - }; - required: (keyof S)[]; -}; - -export function getJsonSchema<S extends Schema>( - schema: S, -): ToJsonSchema<Unflatten<ChartResult<S>>> { - const jsonSchema = { - type: "object", - properties: {} as Record<string, unknown>, - required: [], - }; - - for (const k in schema) { - jsonSchema.properties[k] = { - type: "array", - items: { type: "number" }, - }; - } - - return jsonSchema as ToJsonSchema<Unflatten<ChartResult<S>>>; -} - -/** - * 様々なチャートの管理を司るクラス - */ - -export default abstract class Chart<T extends Schema> { - public schema: T; - - private name: string; - private buffer: { - diff: Commit<T>; - group: string | null; - }[] = []; - // ↓にしたいけどfindOneとかで型エラーになる - //private repositoryForHour: Repository<RawRecord<T>>; - //private repositoryForDay: Repository<RawRecord<T>>; - private repositoryForHour: Repository<{ - id: number; - group?: string | null; - date: number; - }>; - private repositoryForDay: Repository<{ - id: number; - group?: string | null; - date: number; - }>; - - /** - * 1日に一回程度実行されれば良いような計算処理を入れる(主にCASCADE削除などアプリケーション側で感知できない変動によるズレの修正用) - */ - protected abstract tickMajor(group: string | null): Promise<Partial<KVs<T>>>; - - /** - * 少なくとも最小スパン内に1回は実行されて欲しい計算処理を入れる - */ - protected abstract tickMinor(group: string | null): Promise<Partial<KVs<T>>>; - - private static convertSchemaToColumnDefinitions( - schema: Schema, - ): Record<string, { type: string; array?: boolean; default?: any }> { - const columns = {} as Record< - string, - { type: string; array?: boolean; default?: any } - >; - for (const [k, v] of Object.entries(schema)) { - const name = k.replaceAll(".", columnDot); - const type = - v.range === "big" - ? "bigint" - : v.range === "small" - ? "smallint" - : "integer"; - if (v.uniqueIncrement) { - columns[uniqueTempColumnPrefix + name] = { - type: "varchar", - array: true, - default: "{}", - }; - columns[columnPrefix + name] = { - type, - default: 0, - }; - } else { - columns[columnPrefix + name] = { - type, - default: 0, - }; - } - } - return columns; - } - - private static dateToTimestamp(x: Date): number { - return Math.floor(x.getTime() / 1000); - } - - private static parseDate( - date: Date, - ): [number, number, number, number, number, number, number] { - const y = date.getUTCFullYear(); - const m = date.getUTCMonth(); - const d = date.getUTCDate(); - const h = date.getUTCHours(); - const _m = date.getUTCMinutes(); - const _s = date.getUTCSeconds(); - const _ms = date.getUTCMilliseconds(); - - return [y, m, d, h, _m, _s, _ms]; - } - - private static getCurrentDate() { - return Chart.parseDate(new Date()); - } - - public static schemaToEntity( - name: string, - schema: Schema, - grouped = false, - ): { - hour: EntitySchema; - day: EntitySchema; - } { - const createEntity = (span: "hour" | "day"): EntitySchema => - new EntitySchema({ - name: - span === "hour" - ? `__chart__${camelToSnake(name)}` - : span === "day" - ? `__chart_day__${camelToSnake(name)}` - : (new Error("not happen") as never), - columns: { - id: { - type: "integer", - primary: true, - generated: true, - }, - date: { - type: "integer", - }, - ...(grouped - ? { - group: { - type: "varchar", - length: 128, - }, - } - : {}), - ...Chart.convertSchemaToColumnDefinitions(schema), - }, - indices: [ - { - columns: grouped ? ["date", "group"] : ["date"], - unique: true, - }, - ], - uniques: [ - { - columns: grouped ? ["date", "group"] : ["date"], - }, - ], - relations: { - /* TODO - group: { - target: () => Foo, - type: 'many-to-one', - onDelete: 'CASCADE', - }, - */ - }, - }); - - return { - hour: createEntity("hour"), - day: createEntity("day"), - }; - } - - constructor(name: string, schema: T, grouped = false) { - this.name = name; - this.schema = schema; - - const { hour, day } = Chart.schemaToEntity(name, schema, grouped); - this.repositoryForHour = db.getRepository<{ - id: number; - group?: string | null; - date: number; - }>(hour); - this.repositoryForDay = db.getRepository<{ - id: number; - group?: string | null; - date: number; - }>(day); - } - - private convertRawRecord(x: RawRecord<T>): KVs<T> { - const kvs = {} as Record<string, number>; - for (const k of Object.keys(x).filter((k) => - k.startsWith(columnPrefix), - ) as (keyof Columns<T>)[]) { - kvs[ - (k as string).substr(columnPrefix.length).split(columnDot).join(".") - ] = x[k]; - } - return kvs as KVs<T>; - } - - private getNewLog(latest: KVs<T> | null): KVs<T> { - const log = {} as Record<keyof T, number>; - for (const [k, v] of Object.entries(this.schema) as [ - keyof typeof this["schema"], - this["schema"][string], - ][]) { - if (v.accumulate && latest) { - log[k] = latest[k]; - } else { - log[k] = 0; - } - } - return log as KVs<T>; - } - - private getLatestLog( - group: string | null, - span: "hour" | "day", - ): Promise<RawRecord<T> | null> { - const repository = - span === "hour" - ? this.repositoryForHour - : span === "day" - ? this.repositoryForDay - : (new Error("not happen") as never); - - return repository - .findOne({ - where: group - ? { - group: group, - } - : {}, - order: { - date: -1, - }, - }) - .then((x) => x ?? null) as Promise<RawRecord<T> | null>; - } - - /** - * 現在(=今のHour or Day)のログをデータベースから探して、あればそれを返し、なければ作成して返します。 - */ - private async claimCurrentLog( - group: string | null, - span: "hour" | "day", - ): Promise<RawRecord<T>> { - const [y, m, d, h] = Chart.getCurrentDate(); - - const current = dateUTC( - span === "hour" - ? [y, m, d, h] - : span === "day" - ? [y, m, d] - : (new Error("not happen") as never), - ); - - const repository = - span === "hour" - ? this.repositoryForHour - : span === "day" - ? this.repositoryForDay - : (new Error("not happen") as never); - - // 現在(=今のHour or Day)のログ - const currentLog = (await repository.findOneBy({ - date: Chart.dateToTimestamp(current), - ...(group ? { group: group } : {}), - })) as RawRecord<T> | undefined; - - // ログがあればそれを返して終了 - if (currentLog != null) { - return currentLog; - } - - let log: RawRecord<T>; - let data: KVs<T>; - - // 集計期間が変わってから、初めてのチャート更新なら - // 最も最近のログを持ってくる - // * 例えば集計期間が「日」である場合で考えると、 - // * 昨日何もチャートを更新するような出来事がなかった場合は、 - // * ログがそもそも作られずドキュメントが存在しないということがあり得るため、 - // * 「昨日の」と決め打ちせずに「もっとも最近の」とします - const latest = await this.getLatestLog(group, span); - - if (latest != null) { - // 空ログデータを作成 - data = this.getNewLog(this.convertRawRecord(latest)); - } else { - // ログが存在しなかったら - // (Misskeyインスタンスを建てて初めてのチャート更新時など) - - // 初期ログデータを作成 - data = this.getNewLog(null); - - logger.info( - `${ - this.name + (group ? `:${group}` : "") - }(${span}): Initial commit created`, - ); - } - - const date = Chart.dateToTimestamp(current); - const lockKey = group - ? `${this.name}:${date}:${span}:${group}` - : `${this.name}:${date}:${span}`; - - const unlock = await getChartInsertLock(lockKey); - try { - // ロック内でもう1回チェックする - const currentLog = (await repository.findOneBy({ - date: date, - ...(group ? { group: group } : {}), - })) as RawRecord<T> | undefined; - - // ログがあればそれを返して終了 - if (currentLog != null) return currentLog; - - const columns = {} as Record<string, number | unknown[]>; - for (const [k, v] of Object.entries(data)) { - const name = k.replaceAll(".", columnDot); - columns[columnPrefix + name] = v; - } - - // 新規ログ挿入 - log = (await repository - .insert({ - date: date, - ...(group ? { group: group } : {}), - ...columns, - }) - .then((x) => - repository.findOneByOrFail(x.identifiers[0]), - )) as RawRecord<T>; - - logger.info( - `${ - this.name + (group ? `:${group}` : "") - }(${span}): New commit created`, - ); - - return log; - } finally { - unlock(); - } - } - - protected commit(diff: Commit<T>, group: string | null = null): void { - for (const [k, v] of Object.entries(diff)) { - if (v == null || v === 0 || (Array.isArray(v) && v.length === 0)) - // rome-ignore lint/performance/noDelete: needs to be deleted not just set to undefined - delete diff[k]; - } - this.buffer.push({ - diff, - group, - }); - } - - public async save(): Promise<void> { - if (this.buffer.length === 0) { - logger.info(`${this.name}: Write skipped`); - return; - } - - // TODO: 前の時間のログがbufferにあった場合のハンドリング - // 例えば、save が20分ごとに行われるとして、前回行われたのは 01:50 だったとする。 - // 次に save が行われるのは 02:10 ということになるが、もし 01:55 に新規ログが buffer に追加されたとすると、 - // そのログは本来は 01:00~ のログとしてDBに保存されて欲しいのに、02:00~ のログ扱いになってしまう。 - // これを回避するための実装は複雑になりそうなため、一旦保留。 - - const update = async ( - logHour: RawRecord<T>, - logDay: RawRecord<T>, - ): Promise<void> => { - const finalDiffs = {} as Record<string, number | string[]>; - - for (const diff of this.buffer - .filter((q) => q.group == null || q.group === logHour.group) - .map((q) => q.diff)) { - for (const [k, v] of Object.entries(diff)) { - if (finalDiffs[k] == null) { - finalDiffs[k] = v; - } else { - if (typeof finalDiffs[k] === "number") { - (finalDiffs[k] as number) += v as number; - } else { - (finalDiffs[k] as string[]) = (finalDiffs[k] as string[]).concat( - v, - ); - } - } - } - } - - const queryForHour: Record<keyof RawRecord<T>, number | (() => string)> = - {} as any; - const queryForDay: Record<keyof RawRecord<T>, number | (() => string)> = - {} as any; - for (const [k, v] of Object.entries(finalDiffs)) { - if (typeof v === "number") { - const name = (columnPrefix + - k.replaceAll(".", columnDot)) as keyof Columns<T>; - if (v > 0) queryForHour[name] = () => `"${name}" + ${v}`; - if (v < 0) queryForHour[name] = () => `"${name}" - ${Math.abs(v)}`; - if (v > 0) queryForDay[name] = () => `"${name}" + ${v}`; - if (v < 0) queryForDay[name] = () => `"${name}" - ${Math.abs(v)}`; - } else if (Array.isArray(v) && v.length > 0) { - // ユニークインクリメント - const tempColumnName = (uniqueTempColumnPrefix + - k.replaceAll(".", columnDot)) as keyof TempColumnsForUnique<T>; - // TODO: item をSQLエスケープ - const itemsForHour = v - .filter((item) => !logHour[tempColumnName].includes(item)) - .map((item) => `"${item}"`); - const itemsForDay = v - .filter((item) => !logDay[tempColumnName].includes(item)) - .map((item) => `"${item}"`); - if (itemsForHour.length > 0) - queryForHour[tempColumnName] = () => - `array_cat("${tempColumnName}", '{${itemsForHour.join( - ",", - )}}'::varchar[])`; - if (itemsForDay.length > 0) - queryForDay[tempColumnName] = () => - `array_cat("${tempColumnName}", '{${itemsForDay.join( - ",", - )}}'::varchar[])`; - } - } - - // bake unique count - for (const [k, v] of Object.entries(finalDiffs)) { - if ( - this.schema[k].uniqueIncrement && - Array.isArray(v) && - v.length > 0 - ) { - const name = (columnPrefix + - k.replaceAll(".", columnDot)) as keyof Columns<T>; - const tempColumnName = (uniqueTempColumnPrefix + - k.replaceAll(".", columnDot)) as keyof TempColumnsForUnique<T>; - queryForHour[name] = new Set([ - ...(v as string[]), - ...logHour[tempColumnName], - ]).size; - queryForDay[name] = new Set([ - ...(v as string[]), - ...logDay[tempColumnName], - ]).size; - } - } - - // compute intersection - // TODO: intersectionに指定されたカラムがintersectionだった場合の対応 - for (const [k, v] of Object.entries(this.schema)) { - const intersection = v.intersection; - if (intersection) { - const name = (columnPrefix + - k.replaceAll(".", columnDot)) as keyof Columns<T>; - const firstKey = intersection[0]; - const firstTempColumnName = (uniqueTempColumnPrefix + - firstKey.replaceAll( - ".", - columnDot, - )) as keyof TempColumnsForUnique<T>; - const firstValues = finalDiffs[firstKey] as string[] | undefined; - const currentValuesForHour = new Set([ - ...(firstValues ?? []), - ...logHour[firstTempColumnName], - ]); - const currentValuesForDay = new Set([ - ...(firstValues ?? []), - ...logDay[firstTempColumnName], - ]); - for (let i = 1; i < intersection.length; i++) { - const targetKey = intersection[i]; - const targetTempColumnName = (uniqueTempColumnPrefix + - targetKey.replaceAll( - ".", - columnDot, - )) as keyof TempColumnsForUnique<T>; - const targetValues = finalDiffs[targetKey] as string[] | undefined; - const targetValuesForHour = new Set([ - ...(targetValues ?? []), - ...logHour[targetTempColumnName], - ]); - const targetValuesForDay = new Set([ - ...(targetValues ?? []), - ...logDay[targetTempColumnName], - ]); - currentValuesForHour.forEach((v) => { - if (!targetValuesForHour.has(v)) currentValuesForHour.delete(v); - }); - currentValuesForDay.forEach((v) => { - if (!targetValuesForDay.has(v)) currentValuesForDay.delete(v); - }); - } - queryForHour[name] = currentValuesForHour.size; - queryForDay[name] = currentValuesForDay.size; - } - } - - // ログ更新 - await Promise.all([ - this.repositoryForHour - .createQueryBuilder() - .update() - .set(queryForHour as any) - .where("id = :id", { id: logHour.id }) - .execute(), - this.repositoryForDay - .createQueryBuilder() - .update() - .set(queryForDay as any) - .where("id = :id", { id: logDay.id }) - .execute(), - ]); - - logger.info( - `${this.name + (logHour.group ? `:${logHour.group}` : "")}: Updated`, - ); - - // TODO: この一連の処理が始まった後に新たにbufferに入ったものは消さないようにする - this.buffer = this.buffer.filter( - (q) => q.group != null && q.group !== logHour.group, - ); - }; - - const startCount = this.buffer.length; - - const groups = removeDuplicates(this.buffer.map((log) => log.group)); - const groupCount = groups.length; - - // Limit the number of concurrent chart update queries executed on the database - // to 25 at a time, so as avoid excessive IO spinlocks like when 8k queries are - // sent out at once. - const limit = promiseLimit(25); - - const startTime = Date.now(); - await Promise.all( - groups.map((group) => - limit(() => - Promise.all([ - this.claimCurrentLog(group, "hour"), - this.claimCurrentLog(group, "day"), - ]).then(([logHour, logDay]) => update(logHour, logDay)), - ), - ), - ); - - const duration = Date.now() - startTime; - logger.info( - `Saved ${startCount} (${groupCount} unique) ${this.name} items in ${duration}ms (${this.buffer.length} remaining)`, - ); - } - - public async tick( - major: boolean, - group: string | null = null, - ): Promise<void> { - const data = major - ? await this.tickMajor(group) - : await this.tickMinor(group); - - const columns = {} as Record<keyof Columns<T>, number>; - for (const [k, v] of Object.entries(data) as [ - keyof typeof data, - number, - ][]) { - const name = (columnPrefix + - (k as string).replaceAll(".", columnDot)) as keyof Columns<T>; - columns[name] = v; - } - - if (Object.keys(columns).length === 0) { - return; - } - - const update = async ( - logHour: RawRecord<T>, - logDay: RawRecord<T>, - ): Promise<void> => { - await Promise.all([ - this.repositoryForHour - .createQueryBuilder() - .update() - .set(columns) - .where("id = :id", { id: logHour.id }) - .execute(), - this.repositoryForDay - .createQueryBuilder() - .update() - .set(columns) - .where("id = :id", { id: logDay.id }) - .execute(), - ]); - }; - - return Promise.all([ - this.claimCurrentLog(group, "hour"), - this.claimCurrentLog(group, "day"), - ]).then(([logHour, logDay]) => update(logHour, logDay)); - } - - public resync(group: string | null = null): Promise<void> { - return this.tick(true, group); - } - - public async clean(): Promise<void> { - const current = dateUTC(Chart.getCurrentDate()); - - // 一日以上前かつ三日以内 - const gt = Chart.dateToTimestamp(current) - 60 * 60 * 24 * 3; - const lt = Chart.dateToTimestamp(current) - 60 * 60 * 24; - - const columns = {} as Record<keyof TempColumnsForUnique<T>, []>; - for (const [k, v] of Object.entries(this.schema)) { - if (v.uniqueIncrement) { - const name = (uniqueTempColumnPrefix + - k.replaceAll(".", columnDot)) as keyof TempColumnsForUnique<T>; - columns[name] = []; - } - } - - if (Object.keys(columns).length === 0) { - return; - } - - await Promise.all([ - this.repositoryForHour - .createQueryBuilder() - .update() - .set(columns) - .where("date > :gt", { gt }) - .andWhere("date < :lt", { lt }) - .execute(), - this.repositoryForDay - .createQueryBuilder() - .update() - .set(columns) - .where("date > :gt", { gt }) - .andWhere("date < :lt", { lt }) - .execute(), - ]); - } - - public async getChartRaw( - span: "hour" | "day", - amount: number, - cursor: Date | null, - group: string | null = null, - ): Promise<ChartResult<T>> { - const [y, m, d, h, _m, _s, _ms] = cursor - ? Chart.parseDate(subtractTime(addTime(cursor, 1, span), 1)) - : Chart.getCurrentDate(); - const [y2, m2, d2, h2] = cursor - ? Chart.parseDate(addTime(cursor, 1, span)) - : ([] as never); - - const lt = dateUTC([y, m, d, h, _m, _s, _ms]); - - const gt = - span === "day" - ? subtractTime( - cursor ? dateUTC([y2, m2, d2, 0]) : dateUTC([y, m, d, 0]), - amount - 1, - "day", - ) - : span === "hour" - ? subtractTime( - cursor ? dateUTC([y2, m2, d2, h2]) : dateUTC([y, m, d, h]), - amount - 1, - "hour", - ) - : (new Error("not happen") as never); - - const repository = - span === "hour" - ? this.repositoryForHour - : span === "day" - ? this.repositoryForDay - : (new Error("not happen") as never); - - // ログ取得 - let logs = (await repository.find({ - where: { - date: Between(Chart.dateToTimestamp(gt), Chart.dateToTimestamp(lt)), - ...(group ? { group: group } : {}), - }, - order: { - date: -1, - }, - })) as RawRecord<T>[]; - - // 要求された範囲にログがひとつもなかったら - if (logs.length === 0) { - // もっとも新しいログを持ってくる - // (すくなくともひとつログが無いと隙間埋めできないため) - const recentLog = (await repository.findOne({ - where: group - ? { - group: group, - } - : {}, - order: { - date: -1, - }, - })) as RawRecord<T> | undefined; - - if (recentLog) { - logs = [recentLog]; - } - - // 要求された範囲の最も古い箇所に位置するログが存在しなかったら - } else if (!isTimeSame(new Date(logs[logs.length - 1].date * 1000), gt)) { - // 要求された範囲の最も古い箇所時点での最も新しいログを持ってきて末尾に追加する - // (隙間埋めできないため) - const outdatedLog = (await repository.findOne({ - where: { - date: LessThan(Chart.dateToTimestamp(gt)), - ...(group ? { group: group } : {}), - }, - order: { - date: -1, - }, - })) as RawRecord<T> | undefined; - - if (outdatedLog) { - logs.push(outdatedLog); - } - } - - const chart: KVs<T>[] = []; - - for (let i = amount - 1; i >= 0; i--) { - const current = - span === "hour" - ? subtractTime(dateUTC([y, m, d, h]), i, "hour") - : span === "day" - ? subtractTime(dateUTC([y, m, d]), i, "day") - : (new Error("not happen") as never); - - const log = logs.find((l) => - isTimeSame(new Date(l.date * 1000), current), - ); - - if (log) { - chart.unshift(this.convertRawRecord(log)); - } else { - // 隙間埋め - const latest = logs.find((l) => - isTimeBefore(new Date(l.date * 1000), current), - ); - const data = latest ? this.convertRawRecord(latest) : null; - chart.unshift(this.getNewLog(data)); - } - } - - const res = {} as ChartResult<T>; - - /** - * [{ foo: 1, bar: 5 }, { foo: 2, bar: 6 }, { foo: 3, bar: 7 }] - * を - * { foo: [1, 2, 3], bar: [5, 6, 7] } - * にする - */ - for (const record of chart) { - for (const [k, v] of Object.entries(record) as [ - keyof typeof record, - number, - ][]) { - if (res[k]) { - res[k].push(v); - } else { - res[k] = [v]; - } - } - } - - return res; - } - - public async getChart( - span: "hour" | "day", - amount: number, - cursor: Date | null, - group: string | null = null, - ): Promise<Unflatten<ChartResult<T>>> { - const result = await this.getChartRaw(span, amount, cursor, group); - const object = {}; - for (const [k, v] of Object.entries(result)) { - nestedProperty.set(object, k, v); - } - return object as Unflatten<ChartResult<T>>; - } -} diff --git a/packages/backend/src/services/chart/entities.ts b/packages/backend/src/services/chart/entities.ts deleted file mode 100644 index e203dffdff..0000000000 --- a/packages/backend/src/services/chart/entities.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { entity as FederationChart } from "./charts/entities/federation.js"; -import { entity as NotesChart } from "./charts/entities/notes.js"; -import { entity as UsersChart } from "./charts/entities/users.js"; -import { entity as ActiveUsersChart } from "./charts/entities/active-users.js"; -import { entity as InstanceChart } from "./charts/entities/instance.js"; -import { entity as PerUserNotesChart } from "./charts/entities/per-user-notes.js"; -import { entity as DriveChart } from "./charts/entities/drive.js"; -import { entity as PerUserReactionsChart } from "./charts/entities/per-user-reactions.js"; -import { entity as HashtagChart } from "./charts/entities/hashtag.js"; -import { entity as PerUserFollowingChart } from "./charts/entities/per-user-following.js"; -import { entity as PerUserDriveChart } from "./charts/entities/per-user-drive.js"; -import { entity as ApRequestChart } from "./charts/entities/ap-request.js"; - -import { entity as TestChart } from "./charts/entities/test.js"; -import { entity as TestGroupedChart } from "./charts/entities/test-grouped.js"; -import { entity as TestUniqueChart } from "./charts/entities/test-unique.js"; -import { entity as TestIntersectionChart } from "./charts/entities/test-intersection.js"; - -export const entities = [ - FederationChart.hour, - FederationChart.day, - NotesChart.hour, - NotesChart.day, - UsersChart.hour, - UsersChart.day, - ActiveUsersChart.hour, - ActiveUsersChart.day, - InstanceChart.hour, - InstanceChart.day, - PerUserNotesChart.hour, - PerUserNotesChart.day, - DriveChart.hour, - DriveChart.day, - PerUserReactionsChart.hour, - PerUserReactionsChart.day, - HashtagChart.hour, - HashtagChart.day, - PerUserFollowingChart.hour, - PerUserFollowingChart.day, - PerUserDriveChart.hour, - PerUserDriveChart.day, - ApRequestChart.hour, - ApRequestChart.day, - - ...(process.env.NODE_ENV === "test" - ? [ - TestChart.hour, - TestChart.day, - TestGroupedChart.hour, - TestGroupedChart.day, - TestUniqueChart.hour, - TestUniqueChart.day, - TestIntersectionChart.hour, - TestIntersectionChart.day, - ] - : []), -]; diff --git a/packages/backend/src/services/chart/index.ts b/packages/backend/src/services/chart/index.ts deleted file mode 100644 index 969cdab6d7..0000000000 --- a/packages/backend/src/services/chart/index.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { beforeShutdown } from "@/misc/before-shutdown.js"; - -import FederationChart from "./charts/federation.js"; -import NotesChart from "./charts/notes.js"; -import UsersChart from "./charts/users.js"; -import ActiveUsersChart from "./charts/active-users.js"; -import InstanceChart from "./charts/instance.js"; -import PerUserNotesChart from "./charts/per-user-notes.js"; -import DriveChart from "./charts/drive.js"; -import PerUserReactionsChart from "./charts/per-user-reactions.js"; -import HashtagChart from "./charts/hashtag.js"; -import PerUserFollowingChart from "./charts/per-user-following.js"; -import PerUserDriveChart from "./charts/per-user-drive.js"; -import ApRequestChart from "./charts/ap-request.js"; - -export const federationChart = new FederationChart(); -export const notesChart = new NotesChart(); -export const usersChart = new UsersChart(); -export const activeUsersChart = new ActiveUsersChart(); -export const instanceChart = new InstanceChart(); -export const perUserNotesChart = new PerUserNotesChart(); -export const driveChart = new DriveChart(); -export const perUserReactionsChart = new PerUserReactionsChart(); -export const hashtagChart = new HashtagChart(); -export const perUserFollowingChart = new PerUserFollowingChart(); -export const perUserDriveChart = new PerUserDriveChart(); -export const apRequestChart = new ApRequestChart(); - -const charts = [ - federationChart, - notesChart, - usersChart, - activeUsersChart, - instanceChart, - perUserNotesChart, - driveChart, - perUserReactionsChart, - hashtagChart, - perUserFollowingChart, - perUserDriveChart, - apRequestChart, -]; - -// 20分おきにメモリ情報をDBに書き込み -setInterval(() => { - for (const chart of charts) { - chart.save(); - } -}, 1000 * 60 * 20); - -beforeShutdown(() => Promise.all(charts.map((chart) => chart.save()))); diff --git a/packages/backend/src/services/create-notification.ts b/packages/backend/src/services/create-notification.ts deleted file mode 100644 index f6545b131c..0000000000 --- a/packages/backend/src/services/create-notification.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { publishMainStream } from "@/services/stream.js"; -import { pushNotification } from "@/services/push-notification.js"; -import { - Notifications, - Mutings, - NoteThreadMutings, - UserProfiles, - Users, -} from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import type { User } from "@/models/entities/user.js"; -import type { Notification } from "@/models/entities/notification.js"; -import { sendEmailNotification } from "./send-email-notification.js"; - -export async function createNotification( - notifieeId: User["id"], - type: Notification["type"], - data: Partial<Notification>, -) { - if (data.notifierId && notifieeId === data.notifierId) { - return null; - } - - const profile = await UserProfiles.findOneBy({ userId: notifieeId }); - - const isMuted = profile?.mutingNotificationTypes.includes(type); - - if (data.note != null) { - const threadMute = await NoteThreadMutings.findOneBy({ - userId: notifieeId, - threadId: data.note.threadId || data.note.id, - }); - - if (threadMute) { - return null; - } - } - - // Create notification - const notification = await Notifications.insert({ - id: genId(), - createdAt: new Date(), - notifieeId: notifieeId, - type: type, - // 相手がこの通知をミュートしているようなら、既読を予めつけておく - isRead: isMuted, - ...data, - } as Partial<Notification>).then((x) => - Notifications.findOneByOrFail(x.identifiers[0]), - ); - - const packed = await Notifications.pack(notification, {}); - - // Publish notification event - publishMainStream(notifieeId, "notification", packed); - - // 2秒経っても(今回作成した)通知が既読にならなかったら「未読の通知がありますよ」イベントを発行する - setTimeout(async () => { - const fresh = await Notifications.findOneBy({ id: notification.id }); - if (fresh == null) return; // 既に削除されているかもしれない - if (fresh.isRead) return; - - //#region ただしミュートしているユーザーからの通知なら無視 - const mutings = await Mutings.findBy({ - muterId: notifieeId, - }); - if ( - data.notifierId && - mutings.map((m) => m.muteeId).includes(data.notifierId) - ) { - return; - } - //#endregion - - publishMainStream(notifieeId, "unreadNotification", packed); - pushNotification(notifieeId, "notification", packed); - - if (type === "follow") - sendEmailNotification.follow( - notifieeId, - await Users.findOneByOrFail({ id: data.notifierId! }), - ); - if (type === "receiveFollowRequest") - sendEmailNotification.receiveFollowRequest( - notifieeId, - await Users.findOneByOrFail({ id: data.notifierId! }), - ); - }, 2000); - - return notification; -} diff --git a/packages/backend/src/services/create-system-user.ts b/packages/backend/src/services/create-system-user.ts deleted file mode 100644 index 24536090a9..0000000000 --- a/packages/backend/src/services/create-system-user.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { v4 as uuid } from "uuid"; -import generateNativeUserToken from "../server/api/common/generate-native-user-token.js"; -import { genRsaKeyPair } from "@/misc/gen-key-pair.js"; -import { User } from "@/models/entities/user.js"; -import { UserProfile } from "@/models/entities/user-profile.js"; -import { IsNull } from "typeorm"; -import { genId } from "@/misc/gen-id.js"; -import { UserKeypair } from "@/models/entities/user-keypair.js"; -import { UsedUsername } from "@/models/entities/used-username.js"; -import { db } from "@/db/postgre.js"; -import { hashPassword } from "@/misc/password.js"; - -export async function createSystemUser(username: string) { - const password = uuid(); - - // Generate hash of password - const hash = await hashPassword(password); - - // Generate secret - const secret = generateNativeUserToken(); - - const keyPair = await genRsaKeyPair(4096); - - let account!: User; - - // Start transaction - await db.transaction(async (transactionalEntityManager) => { - const exist = await transactionalEntityManager.findOneBy(User, { - usernameLower: username.toLowerCase(), - host: IsNull(), - }); - - if (exist) throw new Error("the user is already exists"); - - account = await transactionalEntityManager - .insert(User, { - id: genId(), - createdAt: new Date(), - username: username, - usernameLower: username.toLowerCase(), - host: null, - token: secret, - isAdmin: false, - isLocked: true, - isExplorable: false, - isBot: true, - }) - .then((x) => - transactionalEntityManager.findOneByOrFail(User, x.identifiers[0]), - ); - - await transactionalEntityManager.insert(UserKeypair, { - publicKey: keyPair.publicKey, - privateKey: keyPair.privateKey, - userId: account.id, - }); - - await transactionalEntityManager.insert(UserProfile, { - userId: account.id, - autoAcceptFollowed: false, - password: hash, - }); - - await transactionalEntityManager.insert(UsedUsername, { - createdAt: new Date(), - username: username.toLowerCase(), - }); - }); - - return account; -} diff --git a/packages/backend/src/services/delete-account.ts b/packages/backend/src/services/delete-account.ts deleted file mode 100644 index 927776199a..0000000000 --- a/packages/backend/src/services/delete-account.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { Users } from "@/models/index.js"; -import { createDeleteAccountJob } from "@/queue/index.js"; -import { publishUserEvent } from "./stream.js"; -import { doPostSuspend } from "./suspend-user.js"; - -export async function deleteAccount(user: { - id: string; - host: string | null; -}): Promise<void> { - // 物理削除する前にDelete activityを送信する - await doPostSuspend(user).catch((e) => {}); - - createDeleteAccountJob(user, { - soft: false, - }); - - await Users.update(user.id, { - isDeleted: true, - }); - - // Terminate streaming - publishUserEvent(user.id, "terminate", {}); -} diff --git a/packages/backend/src/services/detect-sensitive.ts b/packages/backend/src/services/detect-sensitive.ts deleted file mode 100644 index df695e86da..0000000000 --- a/packages/backend/src/services/detect-sensitive.ts +++ /dev/null @@ -1,55 +0,0 @@ -import * as fs from "node:fs"; -import { fileURLToPath } from "node:url"; -import { dirname } from "node:path"; -import * as nsfw from "nsfwjs"; -import si from "systeminformation"; - -const _filename = fileURLToPath(import.meta.url); -const _dirname = dirname(_filename); - -const REQUIRED_CPU_FLAGS = ["avx2", "fma"]; -let isSupportedCpu: undefined | boolean = undefined; - -let model: nsfw.NSFWJS; - -export async function detectSensitive( - path: string, -): Promise<nsfw.predictionType[] | null> { - try { - if (isSupportedCpu === undefined) { - const cpuFlags = await getCpuFlags(); - isSupportedCpu = REQUIRED_CPU_FLAGS.every((required) => - cpuFlags.includes(required), - ); - } - - if (!isSupportedCpu) { - console.error("This CPU cannot use TensorFlow."); - return null; - } - - const tf = await import("@tensorflow/tfjs-node"); - - if (model == null) - model = await nsfw.load(`file://${_dirname}/../../nsfw-model/`, { - size: 299, - }); - - const buffer = await fs.promises.readFile(path); - const image = (await tf.node.decodeImage(buffer, 3)) as any; - try { - const predictions = await model.classify(image); - return predictions; - } finally { - image.dispose(); - } - } catch (err) { - console.error(err); - return null; - } -} - -async function getCpuFlags(): Promise<string[]> { - const str = await si.cpuFlags(); - return str.split(/\s+/); -} diff --git a/packages/backend/src/services/drive/add-file.ts b/packages/backend/src/services/drive/add-file.ts deleted file mode 100644 index b25375b947..0000000000 --- a/packages/backend/src/services/drive/add-file.ts +++ /dev/null @@ -1,671 +0,0 @@ -import * as fs from "node:fs"; - -import { v4 as uuid } from "uuid"; - -import type S3 from "aws-sdk/clients/s3.js"; -import sharp from "sharp"; -import { IsNull } from "typeorm"; -import { publishMainStream, publishDriveStream } from "@/services/stream.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { contentDisposition } from "@/misc/content-disposition.js"; -import { getFileInfo } from "@/misc/get-file-info.js"; -import { - DriveFiles, - DriveFolders, - Users, - Instances, - UserProfiles, -} from "@/models/index.js"; -import { DriveFile } from "@/models/entities/drive-file.js"; -import type { IRemoteUser, User } from "@/models/entities/user.js"; -import { - driveChart, - perUserDriveChart, - instanceChart, -} from "@/services/chart/index.js"; -import { genId } from "@/misc/gen-id.js"; -import { isDuplicateKeyValueError } from "@/misc/is-duplicate-key-value-error.js"; -import { FILE_TYPE_BROWSERSAFE } from "@/const.js"; -import { IdentifiableError } from "@/misc/identifiable-error.js"; -import { getS3 } from "./s3.js"; -import { InternalStorage } from "./internal-storage.js"; -import type { IImage } from "./image-processor.js"; -import { convertSharpToWebp } from "./image-processor.js"; -import { driveLogger } from "./logger.js"; -import { GenerateVideoThumbnail } from "./generate-video-thumbnail.js"; -import { deleteFile } from "./delete-file.js"; - -const logger = driveLogger.createSubLogger("register", "yellow"); - -/*** - * Save file - * @param path Path for original - * @param name Name for original - * @param type Content-Type for original - * @param hash Hash for original - * @param size Size for original - */ -async function save( - file: DriveFile, - path: string, - name: string, - type: string, - hash: string, - size: number, -): Promise<DriveFile> { - // thunbnail, webpublic を必要なら生成 - const alts = await generateAlts(path, type, !file.uri); - - const meta = await fetchMeta(); - - if (meta.useObjectStorage) { - //#region ObjectStorage params - let [ext] = name.match(/\.([a-zA-Z0-9_-]+)$/) || [""]; - - if (ext === "") { - if (type === "image/jpeg") ext = ".jpg"; - if (type === "image/png") ext = ".png"; - if (type === "image/webp") ext = ".webp"; - if (type === "image/apng") ext = ".apng"; - if (type === "image/avif") ext = ".avif"; - if (type === "image/vnd.mozilla.apng") ext = ".apng"; - } - - // Some cloud providers (notably upcloud) will infer the content-type based - // on extension, so we remove extensions from non-browser-safe types. - if (!FILE_TYPE_BROWSERSAFE.includes(type)) { - ext = ""; - } - - const baseUrl = - meta.objectStorageBaseUrl || - `${meta.objectStorageUseSSL ? "https" : "http"}://${ - meta.objectStorageEndpoint - }${meta.objectStoragePort ? `:${meta.objectStoragePort}` : ""}/${ - meta.objectStorageBucket - }`; - - // for original - const key = `${meta.objectStoragePrefix}/${uuid()}${ext}`; - const url = `${baseUrl}/${key}`; - - // for alts - let webpublicKey: string | null = null; - let webpublicUrl: string | null = null; - let thumbnailKey: string | null = null; - let thumbnailUrl: string | null = null; - //#endregion - - //#region Uploads - logger.info(`uploading original: ${key}`); - const uploads = [upload(key, fs.createReadStream(path), type, name)]; - - if (alts.webpublic) { - webpublicKey = `${meta.objectStoragePrefix}/webpublic-${uuid()}.${ - alts.webpublic.ext - }`; - webpublicUrl = `${baseUrl}/${webpublicKey}`; - - logger.info(`uploading webpublic: ${webpublicKey}`); - uploads.push( - upload(webpublicKey, alts.webpublic.data, alts.webpublic.type, name), - ); - } - - if (alts.thumbnail) { - thumbnailKey = `${meta.objectStoragePrefix}/thumbnail-${uuid()}.${ - alts.thumbnail.ext - }`; - thumbnailUrl = `${baseUrl}/${thumbnailKey}`; - - logger.info(`uploading thumbnail: ${thumbnailKey}`); - uploads.push( - upload(thumbnailKey, alts.thumbnail.data, alts.thumbnail.type), - ); - } - - await Promise.all(uploads); - //#endregion - - file.url = url; - file.thumbnailUrl = thumbnailUrl; - file.webpublicUrl = webpublicUrl; - file.accessKey = key; - file.thumbnailAccessKey = thumbnailKey; - file.webpublicAccessKey = webpublicKey; - file.webpublicType = alts.webpublic?.type ?? null; - file.name = name; - file.type = type; - file.md5 = hash; - file.size = size; - file.storedInternal = false; - - return await DriveFiles.insert(file).then((x) => - DriveFiles.findOneByOrFail(x.identifiers[0]), - ); - } else { - // use internal storage - const accessKey = uuid(); - const thumbnailAccessKey = `thumbnail-${uuid()}`; - const webpublicAccessKey = `webpublic-${uuid()}`; - - const url = InternalStorage.saveFromPath(accessKey, path); - - let thumbnailUrl: string | null = null; - let webpublicUrl: string | null = null; - - if (alts.thumbnail) { - thumbnailUrl = InternalStorage.saveFromBuffer( - thumbnailAccessKey, - alts.thumbnail.data, - ); - logger.info(`thumbnail stored: ${thumbnailAccessKey}`); - } - - if (alts.webpublic) { - webpublicUrl = InternalStorage.saveFromBuffer( - webpublicAccessKey, - alts.webpublic.data, - ); - logger.info(`web stored: ${webpublicAccessKey}`); - } - - file.storedInternal = true; - file.url = url; - file.thumbnailUrl = thumbnailUrl; - file.webpublicUrl = webpublicUrl; - file.accessKey = accessKey; - file.thumbnailAccessKey = thumbnailAccessKey; - file.webpublicAccessKey = webpublicAccessKey; - file.webpublicType = alts.webpublic?.type ?? null; - file.name = name; - file.type = type; - file.md5 = hash; - file.size = size; - - return await DriveFiles.insert(file).then((x) => - DriveFiles.findOneByOrFail(x.identifiers[0]), - ); - } -} - -/** - * Generate webpublic, thumbnail, etc - * @param path Path for original - * @param type Content-Type for original - * @param generateWeb Generate webpublic or not - */ -export async function generateAlts( - path: string, - type: string, - generateWeb: boolean, -) { - if (type.startsWith("video/")) { - try { - const thumbnail = await GenerateVideoThumbnail(path); - return { - webpublic: null, - thumbnail, - }; - } catch (err) { - logger.warn(`GenerateVideoThumbnail failed: ${err}`); - return { - webpublic: null, - thumbnail: null, - }; - } - } - - if ( - ![ - "image/jpeg", - "image/png", - "image/webp", - "image/svg+xml", - "image/avif", - ].includes(type) - ) { - logger.debug("web image and thumbnail not created (not an required file)"); - return { - webpublic: null, - thumbnail: null, - }; - } - - let img: sharp.Sharp | null = null; - let satisfyWebpublic: boolean; - - try { - img = sharp(path); - const metadata = await img.metadata(); - const isAnimated = metadata.pages && metadata.pages > 1; - - // skip animated - if (isAnimated) { - return { - webpublic: null, - thumbnail: null, - }; - } - - satisfyWebpublic = !!( - type !== "image/svg+xml" && - type !== "image/webp" && - !( - metadata.exif || - metadata.iptc || - metadata.xmp || - metadata.tifftagPhotoshop - ) && - metadata.width && - metadata.width <= 2048 && - metadata.height && - metadata.height <= 2048 - ); - } catch (err) { - logger.warn(`sharp failed: ${err}`); - return { - webpublic: null, - thumbnail: null, - }; - } - - // #region webpublic - let webpublic: IImage | null = null; - - if (generateWeb && !satisfyWebpublic) { - logger.info("creating web image"); - - try { - if (["image/jpeg"].includes(type)) { - webpublic = await convertSharpToWebp(img, 2048, 2048); - } else if (["image/webp"].includes(type)) { - webpublic = await convertSharpToWebp(img, 2048, 2048); - } else if (["image/png"].includes(type)) { - webpublic = await convertSharpToWebp(img, 2048, 2048, 100); - } else if (["image/svg+xml"].includes(type)) { - webpublic = await convertSharpToWebp(img, 2048, 2048); - } else { - logger.debug("web image not created (not an required image)"); - } - } catch (err) { - logger.warn("web image not created (an error occured)", err as Error); - } - } else { - if (satisfyWebpublic) - logger.info("web image not created (original satisfies webpublic)"); - else logger.info("web image not created (from remote)"); - } - // #endregion webpublic - - // #region thumbnail - let thumbnail: IImage | null = null; - - try { - if ( - [ - "image/jpeg", - "image/webp", - "image/png", - "image/svg+xml", - "image/avif", - ].includes(type) - ) { - thumbnail = await convertSharpToWebp(img, 996, 560); - } else { - logger.debug("thumbnail not created (not an required file)"); - } - } catch (err) { - logger.warn("thumbnail not created (an error occured)", err as Error); - } - // #endregion thumbnail - - return { - webpublic, - thumbnail, - }; -} - -/** - * Upload to ObjectStorage - */ -async function upload( - key: string, - stream: fs.ReadStream | Buffer, - type: string, - filename?: string, -) { - if (type === "image/apng") type = "image/png"; - if (!FILE_TYPE_BROWSERSAFE.includes(type)) type = "application/octet-stream"; - - const meta = await fetchMeta(); - - const params = { - Bucket: meta.objectStorageBucket, - Key: key, - Body: stream, - ContentType: type, - CacheControl: "max-age=31536000, immutable", - } as S3.PutObjectRequest; - - if (filename) - params.ContentDisposition = contentDisposition("inline", filename); - if (meta.objectStorageSetPublicRead) params.ACL = "public-read"; - - const s3 = getS3(meta); - - const upload = s3.upload(params, { - partSize: - s3.endpoint.hostname === "storage.googleapis.com" - ? 500 * 1024 * 1024 - : 8 * 1024 * 1024, - }); - - const result = await upload.promise(); - if (result) - logger.debug( - `Uploaded: ${result.Bucket}/${result.Key} => ${result.Location}`, - ); -} - -async function deleteOldFile(user: IRemoteUser) { - const q = DriveFiles.createQueryBuilder("file") - .where("file.userId = :userId", { userId: user.id }) - .andWhere("file.isLink = FALSE"); - - if (user.avatarId) { - q.andWhere("file.id != :avatarId", { avatarId: user.avatarId }); - } - - if (user.bannerId) { - q.andWhere("file.id != :bannerId", { bannerId: user.bannerId }); - } - - q.orderBy("file.id", "ASC"); - - const oldFile = await q.getOne(); - - if (oldFile) { - deleteFile(oldFile, true); - } -} - -type AddFileArgs = { - /** User who wish to add file */ - user: { - id: User["id"]; - host: User["host"]; - driveCapacityOverrideMb: User["driveCapacityOverrideMb"]; - } | null; - /** File path */ - path: string; - /** Name */ - name?: string | null; - /** Comment */ - comment?: string | null; - /** Folder ID */ - folderId?: any; - /** If set to true, forcibly upload the file even if there is a file with the same hash. */ - force?: boolean; - /** Do not save file to local */ - isLink?: boolean; - /** URL of source (URLからアップロードされた場合(ローカル/リモート)の元URL) */ - url?: string | null; - /** URL of source (リモートインスタンスのURLからアップロードされた場合の元URL) */ - uri?: string | null; - /** Mark file as sensitive */ - sensitive?: boolean | null; - - requestIp?: string | null; - requestHeaders?: Record<string, string> | null; -}; - -/** - * Add file to drive - * - */ -export async function addFile({ - user, - path, - name = null, - comment = null, - folderId = null, - force = false, - isLink = false, - url = null, - uri = null, - sensitive = null, - requestIp = null, - requestHeaders = null, -}: AddFileArgs): Promise<DriveFile> { - let skipNsfwCheck = false; - const instance = await fetchMeta(); - if (user == null) skipNsfwCheck = true; - if (instance.sensitiveMediaDetection === "none") skipNsfwCheck = true; - if ( - user && - instance.sensitiveMediaDetection === "local" && - Users.isRemoteUser(user) - ) - skipNsfwCheck = true; - if ( - user && - instance.sensitiveMediaDetection === "remote" && - Users.isLocalUser(user) - ) - skipNsfwCheck = true; - - const info = await getFileInfo(path, { - skipSensitiveDetection: skipNsfwCheck, - sensitiveThreshold: // 感度が高いほどしきい値は低くすることになる - instance.sensitiveMediaDetectionSensitivity === "veryHigh" - ? 0.1 - : instance.sensitiveMediaDetectionSensitivity === "high" - ? 0.3 - : instance.sensitiveMediaDetectionSensitivity === "low" - ? 0.7 - : instance.sensitiveMediaDetectionSensitivity === "veryLow" - ? 0.9 - : 0.5, - sensitiveThresholdForPorn: 0.75, - enableSensitiveMediaDetectionForVideos: - instance.enableSensitiveMediaDetectionForVideos, - }); - logger.info(`${JSON.stringify(info)}`); - - // 現状 false positive が多すぎて実用に耐えない - //if (info.porn && instance.disallowUploadWhenPredictedAsPorn) { - // throw new IdentifiableError('282f77bf-5816-4f72-9264-aa14d8261a21', 'Detected as porn.'); - //} - - // detect name - const detectedName = - name || (info.type.ext ? `untitled.${info.type.ext}` : "untitled"); - - if (user && !force) { - // Check if there is a file with the same hash - const much = await DriveFiles.findOneBy({ - md5: info.md5, - userId: user.id, - }); - - if (much) { - logger.info(`file with same hash is found: ${much.id}`); - return much; - } - } - - //#region Check drive usage - if (user && !isLink) { - const usage = await DriveFiles.calcDriveUsageOf(user); - const u = await Users.findOneBy({ id: user.id }); - - const instance = await fetchMeta(); - let driveCapacity = - 1024 * - 1024 * - (Users.isLocalUser(user) - ? instance.localDriveCapacityMb - : instance.remoteDriveCapacityMb); - - if (Users.isLocalUser(user) && u?.driveCapacityOverrideMb != null) { - driveCapacity = 1024 * 1024 * u.driveCapacityOverrideMb; - logger.debug("drive capacity override applied"); - logger.debug( - `overrideCap: ${driveCapacity}bytes, usage: ${usage}bytes, u+s: ${ - usage + info.size - }bytes`, - ); - } - - logger.debug(`drive usage is ${usage} (max: ${driveCapacity})`); - - // If usage limit exceeded - if (usage + info.size > driveCapacity) { - if (Users.isLocalUser(user)) { - throw new IdentifiableError( - "c6244ed2-a39a-4e1c-bf93-f0fbd7764fa6", - "No free space.", - ); - } else { - // (アバターまたはバナーを含まず)最も古いファイルを削除する - deleteOldFile( - (await Users.findOneByOrFail({ id: user.id })) as IRemoteUser, - ); - } - } - } - //#endregion - - const fetchFolder = async () => { - if (!folderId) { - return null; - } - - const driveFolder = await DriveFolders.findOneBy({ - id: folderId, - userId: user ? user.id : IsNull(), - }); - - if (driveFolder == null) throw new Error("folder-not-found"); - - return driveFolder; - }; - - const properties: { - width?: number; - height?: number; - orientation?: number; - } = {}; - - if (info.width) { - properties["width"] = info.width; - properties["height"] = info.height; - } - if (info.orientation != null) { - properties["orientation"] = info.orientation; - } - - const profile = user - ? await UserProfiles.findOneBy({ userId: user.id }) - : null; - - const folder = await fetchFolder(); - - let file = new DriveFile(); - file.id = genId(); - file.createdAt = new Date(); - file.userId = user ? user.id : null; - file.userHost = user ? user.host : null; - file.folderId = folder !== null ? folder.id : null; - file.comment = comment; - file.properties = properties; - file.blurhash = info.blurhash || null; - file.isLink = isLink; - file.requestIp = requestIp; - file.requestHeaders = requestHeaders; - file.maybeSensitive = info.sensitive; - file.maybePorn = info.porn; - file.isSensitive = user - ? Users.isLocalUser(user) && profile!.alwaysMarkNsfw - ? true - : sensitive !== null && sensitive !== undefined - ? sensitive - : false - : false; - - if (info.sensitive && profile!.autoSensitive) file.isSensitive = true; - if (info.sensitive && instance.setSensitiveFlagAutomatically) - file.isSensitive = true; - - if (url !== null) { - file.src = url; - - if (isLink) { - file.url = url; - // ローカルプロキシ用 - file.accessKey = uuid(); - file.thumbnailAccessKey = `thumbnail-${uuid()}`; - file.webpublicAccessKey = `webpublic-${uuid()}`; - } - } - - if (uri !== null) { - file.uri = uri; - } - - if (isLink) { - try { - file.size = 0; - file.md5 = info.md5; - file.name = detectedName; - file.type = info.type.mime; - file.storedInternal = false; - - file = await DriveFiles.insert(file).then((x) => - DriveFiles.findOneByOrFail(x.identifiers[0]), - ); - } catch (err) { - // duplicate key error (when already registered) - if (isDuplicateKeyValueError(err)) { - logger.info(`already registered ${file.uri}`); - - file = (await DriveFiles.findOneBy({ - uri: file.uri!, - userId: user ? user.id : IsNull(), - })) as DriveFile; - } else { - logger.error(err as Error); - throw err; - } - } - } else { - file = await save( - file, - path, - detectedName, - info.type.mime, - info.md5, - info.size, - ); - } - - logger.succ(`drive file has been created ${file.id}`); - - if (user) { - DriveFiles.pack(file, { self: true }).then((packedFile) => { - // Publish driveFileCreated event - publishMainStream(user.id, "driveFileCreated", packedFile); - publishDriveStream(user.id, "fileCreated", packedFile); - }); - } - - // 統計を更新 - driveChart.update(file, true); - perUserDriveChart.update(file, true); - if (file.userHost !== null) { - instanceChart.updateDrive(file, true); - } - - return file; -} diff --git a/packages/backend/src/services/drive/delete-file.ts b/packages/backend/src/services/drive/delete-file.ts deleted file mode 100644 index 215270df69..0000000000 --- a/packages/backend/src/services/drive/delete-file.ts +++ /dev/null @@ -1,107 +0,0 @@ -import type { DriveFile } from "@/models/entities/drive-file.js"; -import { InternalStorage } from "./internal-storage.js"; -import { DriveFiles, Instances } from "@/models/index.js"; -import { - driveChart, - perUserDriveChart, - instanceChart, -} from "@/services/chart/index.js"; -import { createDeleteObjectStorageFileJob } from "@/queue/index.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import { getS3 } from "./s3.js"; -import { v4 as uuid } from "uuid"; - -export async function deleteFile(file: DriveFile, isExpired = false) { - if (file.storedInternal) { - InternalStorage.del(file.accessKey!); - - if (file.thumbnailUrl) { - InternalStorage.del(file.thumbnailAccessKey!); - } - - if (file.webpublicUrl) { - InternalStorage.del(file.webpublicAccessKey!); - } - } else if (!file.isLink) { - createDeleteObjectStorageFileJob(file.accessKey!); - - if (file.thumbnailUrl) { - createDeleteObjectStorageFileJob(file.thumbnailAccessKey!); - } - - if (file.webpublicUrl) { - createDeleteObjectStorageFileJob(file.webpublicAccessKey!); - } - } - - postProcess(file, isExpired); -} - -export async function deleteFileSync(file: DriveFile, isExpired = false) { - if (file.storedInternal) { - InternalStorage.del(file.accessKey!); - - if (file.thumbnailUrl) { - InternalStorage.del(file.thumbnailAccessKey!); - } - - if (file.webpublicUrl) { - InternalStorage.del(file.webpublicAccessKey!); - } - } else if (!file.isLink) { - const promises = []; - - promises.push(deleteObjectStorageFile(file.accessKey!)); - - if (file.thumbnailUrl) { - promises.push(deleteObjectStorageFile(file.thumbnailAccessKey!)); - } - - if (file.webpublicUrl) { - promises.push(deleteObjectStorageFile(file.webpublicAccessKey!)); - } - - await Promise.all(promises); - } - - postProcess(file, isExpired); -} - -async function postProcess(file: DriveFile, isExpired = false) { - // リモートファイル期限切れ削除後は直リンクにする - if (isExpired && file.userHost !== null && file.uri != null) { - DriveFiles.update(file.id, { - isLink: true, - url: file.uri, - thumbnailUrl: null, - webpublicUrl: null, - storedInternal: false, - // ローカルプロキシ用 - accessKey: uuid(), - thumbnailAccessKey: `thumbnail-${uuid()}`, - webpublicAccessKey: `webpublic-${uuid()}`, - }); - } else { - DriveFiles.delete(file.id); - } - - // 統計を更新 - driveChart.update(file, false); - perUserDriveChart.update(file, false); - if (file.userHost !== null) { - instanceChart.updateDrive(file, false); - } -} - -export async function deleteObjectStorageFile(key: string) { - const meta = await fetchMeta(); - - const s3 = getS3(meta); - - await s3 - .deleteObject({ - Bucket: meta.objectStorageBucket!, - Key: key, - }) - .promise(); -} diff --git a/packages/backend/src/services/drive/generate-video-thumbnail.ts b/packages/backend/src/services/drive/generate-video-thumbnail.ts deleted file mode 100644 index 356623e79a..0000000000 --- a/packages/backend/src/services/drive/generate-video-thumbnail.ts +++ /dev/null @@ -1,29 +0,0 @@ -import * as fs from "node:fs"; -import { createTempDir } from "@/misc/create-temp.js"; -import type { IImage } from "./image-processor.js"; -import { convertToWebp } from "./image-processor.js"; -import FFmpeg from "fluent-ffmpeg"; - -export async function GenerateVideoThumbnail(source: string): Promise<IImage> { - const [dir, cleanup] = await createTempDir(); - - try { - await new Promise((res, rej) => { - FFmpeg({ - source, - }) - .on("end", res) - .on("error", rej) - .screenshot({ - folder: dir, - filename: "out.png", // must have .png extension - count: 1, - timestamps: ["5%"], - }); - }); - - return await convertToWebp(`${dir}/out.png`, 996, 560); - } finally { - cleanup(); - } -} diff --git a/packages/backend/src/services/drive/image-processor.ts b/packages/backend/src/services/drive/image-processor.ts deleted file mode 100644 index 55869f478f..0000000000 --- a/packages/backend/src/services/drive/image-processor.ts +++ /dev/null @@ -1,44 +0,0 @@ -import sharp from "sharp"; - -export type IImage = { - data: Buffer; - ext: string | null; - type: string; -}; - -/** - * Convert to WebP - * with resize, remove metadata, resolve orientation, stop animation - */ -export async function convertToWebp( - path: string, - width: number, - height: number, - quality: number = 85, -): Promise<IImage> { - return convertSharpToWebp(await sharp(path), width, height, quality); -} - -export async function convertSharpToWebp( - sharp: sharp.Sharp, - width: number, - height: number, - quality: number = 85, -): Promise<IImage> { - const data = await sharp - .resize(width, height, { - fit: "inside", - withoutEnlargement: true, - }) - .rotate() - .webp({ - quality, - }) - .toBuffer(); - - return { - data, - ext: "webp", - type: "image/webp", - }; -} diff --git a/packages/backend/src/services/drive/internal-storage.ts b/packages/backend/src/services/drive/internal-storage.ts deleted file mode 100644 index bccb123be4..0000000000 --- a/packages/backend/src/services/drive/internal-storage.ts +++ /dev/null @@ -1,35 +0,0 @@ -import * as fs from "node:fs"; -import * as Path from "node:path"; -import { fileURLToPath } from "node:url"; -import { dirname } from "node:path"; -import config from "@/config/index.js"; - -const _filename = fileURLToPath(import.meta.url); -const _dirname = dirname(_filename); - -export class InternalStorage { - private static readonly path = Path.resolve(_dirname, "../../../../../files"); - - public static resolvePath = (key: string) => - Path.resolve(InternalStorage.path, key); - - public static read(key: string) { - return fs.createReadStream(InternalStorage.resolvePath(key)); - } - - public static saveFromPath(key: string, srcPath: string) { - fs.mkdirSync(InternalStorage.path, { recursive: true }); - fs.copyFileSync(srcPath, InternalStorage.resolvePath(key)); - return `${config.url}/files/${key}`; - } - - public static saveFromBuffer(key: string, data: Buffer) { - fs.mkdirSync(InternalStorage.path, { recursive: true }); - fs.writeFileSync(InternalStorage.resolvePath(key), data); - return `${config.url}/files/${key}`; - } - - public static del(key: string) { - fs.unlink(InternalStorage.resolvePath(key), () => {}); - } -} diff --git a/packages/backend/src/services/drive/logger.ts b/packages/backend/src/services/drive/logger.ts deleted file mode 100644 index ebde2d7058..0000000000 --- a/packages/backend/src/services/drive/logger.ts +++ /dev/null @@ -1,3 +0,0 @@ -import Logger from "../logger.js"; - -export const driveLogger = new Logger("drive", "blue"); diff --git a/packages/backend/src/services/drive/s3.ts b/packages/backend/src/services/drive/s3.ts deleted file mode 100644 index ca356e9124..0000000000 --- a/packages/backend/src/services/drive/s3.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { URL } from "node:url"; -import S3 from "aws-sdk/clients/s3.js"; -import type { Meta } from "@/models/entities/meta.js"; -import { getAgentByUrl } from "@/misc/fetch.js"; - -export function getS3(meta: Meta) { - const u = - meta.objectStorageEndpoint != null - ? `${meta.objectStorageUseSSL ? "https://" : "http://"}${ - meta.objectStorageEndpoint - }` - : `${meta.objectStorageUseSSL ? "https://" : "http://"}example.net`; - - return new S3({ - endpoint: meta.objectStorageEndpoint || undefined, - accessKeyId: meta.objectStorageAccessKey!, - secretAccessKey: meta.objectStorageSecretKey!, - region: meta.objectStorageRegion || undefined, - sslEnabled: meta.objectStorageUseSSL, - s3ForcePathStyle: !meta.objectStorageEndpoint // AWS with endPoint omitted - ? false - : meta.objectStorageS3ForcePathStyle, - httpOptions: { - agent: getAgentByUrl(new URL(u), !meta.objectStorageUseProxy), - }, - }); -} diff --git a/packages/backend/src/services/drive/upload-from-url.ts b/packages/backend/src/services/drive/upload-from-url.ts deleted file mode 100644 index 9d71757e35..0000000000 --- a/packages/backend/src/services/drive/upload-from-url.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { URL } from "node:url"; -import type { User } from "@/models/entities/user.js"; -import { createTemp } from "@/misc/create-temp.js"; -import { downloadUrl } from "@/misc/download-url.js"; -import type { DriveFolder } from "@/models/entities/drive-folder.js"; -import type { DriveFile } from "@/models/entities/drive-file.js"; -import { DriveFiles } from "@/models/index.js"; -import { driveLogger } from "./logger.js"; -import { addFile } from "./add-file.js"; - -const logger = driveLogger.createSubLogger("downloader"); - -type Args = { - url: string; - user: { id: User["id"]; host: User["host"] } | null; - folderId?: DriveFolder["id"] | null; - uri?: string | null; - sensitive?: boolean; - force?: boolean; - isLink?: boolean; - comment?: string | null; - requestIp?: string | null; - requestHeaders?: Record<string, string> | null; -}; - -export async function uploadFromUrl({ - url, - user, - folderId = null, - uri = null, - sensitive = false, - force = false, - isLink = false, - comment = null, - requestIp = null, - requestHeaders = null, -}: Args): Promise<DriveFile> { - let name = new URL(url).pathname.split("/").pop() || null; - if (name == null || !DriveFiles.validateFileName(name)) { - name = null; - } - - // If the comment is same as the name, skip comment - // (image.name is passed in when receiving attachment) - if (comment !== null && name === comment) { - comment = null; - } - - // Create temp file - const [path, cleanup] = await createTemp(); - - try { - // write content at URL to temp file - await downloadUrl(url, path); - - const driveFile = await addFile({ - user, - path, - name, - comment, - folderId, - force, - isLink, - url, - uri, - sensitive, - requestIp, - requestHeaders, - }); - logger.succ(`Got: ${driveFile.id}`); - return driveFile!; - } catch (e) { - logger.error(`Failed to create drive file: ${e}`, { - url: url, - e: e, - }); - throw e; - } finally { - cleanup(); - } -} diff --git a/packages/backend/src/services/fetch-instance-metadata.ts b/packages/backend/src/services/fetch-instance-metadata.ts deleted file mode 100644 index 79354448f5..0000000000 --- a/packages/backend/src/services/fetch-instance-metadata.ts +++ /dev/null @@ -1,321 +0,0 @@ -import { URL } from "node:url"; -import { JSDOM } from "jsdom"; -import fetch from "node-fetch"; -import tinycolor from "tinycolor2"; -import { getJson, getHtml, getAgentByUrl } from "@/misc/fetch.js"; -import type { Instance } from "@/models/entities/instance.js"; -import { Instances } from "@/models/index.js"; -import { getFetchInstanceMetadataLock } from "@/misc/app-lock.js"; -import Logger from "./logger.js"; -import type { DOMWindow } from "jsdom"; - -const logger = new Logger("metadata", "cyan"); - -export async function fetchInstanceMetadata( - instance: Instance, - force = false, -): Promise<void> { - const unlock = await getFetchInstanceMetadataLock(instance.host); - - if (!force) { - const _instance = await Instances.findOneBy({ host: instance.host }); - const now = Date.now(); - if ( - _instance?.infoUpdatedAt && - now - _instance.infoUpdatedAt.getTime() < 1000 * 60 * 60 * 24 - ) { - unlock(); - return; - } - } - - logger.info(`Fetching metadata of ${instance.host} ...`); - - try { - const [info, dom, manifest] = await Promise.all([ - fetchNodeinfo(instance).catch(() => null), - fetchDom(instance).catch(() => null), - fetchManifest(instance).catch(() => null), - ]); - - const [favicon, icon, themeColor, name, description] = await Promise.all([ - fetchFaviconUrl(instance, dom).catch(() => null), - fetchIconUrl(instance, dom, manifest).catch(() => null), - getThemeColor(info, dom, manifest).catch(() => null), - getSiteName(info, dom, manifest).catch(() => null), - getDescription(info, dom, manifest).catch(() => null), - ]); - - logger.succ(`Successfuly fetched metadata of ${instance.host}`); - - const updates = { - infoUpdatedAt: new Date(), - } as Record<string, any>; - - if (info) { - updates.softwareName = info.software?.name.toLowerCase(); - updates.softwareVersion = info.software?.version; - updates.openRegistrations = info.openRegistrations; - updates.maintainerName = info.metadata - ? info.metadata.maintainer - ? info.metadata.maintainer.name || null - : null - : null; - updates.maintainerEmail = info.metadata - ? info.metadata.maintainer - ? info.metadata.maintainer.email || null - : null - : null; - } - - if (name) updates.name = name; - if (description) updates.description = description; - if (icon || favicon) updates.iconUrl = icon || favicon; - if (favicon) updates.faviconUrl = favicon; - if (themeColor) updates.themeColor = themeColor; - - await Instances.update(instance.id, updates); - - logger.succ(`Successfuly updated metadata of ${instance.host}`); - } catch (e) { - logger.error(`Failed to update metadata of ${instance.host}: ${e}`); - } finally { - unlock(); - } -} - -type NodeInfo = { - openRegistrations?: any; - software?: { - name?: any; - version?: any; - }; - metadata?: { - name?: any; - nodeName?: any; - nodeDescription?: any; - description?: any; - maintainer?: { - name?: any; - email?: any; - }; - }; -}; - -async function fetchNodeinfo(instance: Instance): Promise<NodeInfo> { - logger.info(`Fetching nodeinfo of ${instance.host} ...`); - - try { - const wellknown = (await getJson( - `https://${instance.host}/.well-known/nodeinfo`, - ).catch((e) => { - if (e.statusCode === 404) { - throw new Error("No nodeinfo provided"); - } else { - throw new Error(e.statusCode || e.message); - } - })) as Record<string, unknown>; - - if (wellknown.links == null || !Array.isArray(wellknown.links)) { - throw new Error("No wellknown links"); - } - - const links = wellknown.links as any[]; - - const lnik1_0 = links.find( - (link) => link.rel === "http://nodeinfo.diaspora.software/ns/schema/1.0", - ); - const lnik2_0 = links.find( - (link) => link.rel === "http://nodeinfo.diaspora.software/ns/schema/2.0", - ); - const lnik2_1 = links.find( - (link) => link.rel === "http://nodeinfo.diaspora.software/ns/schema/2.1", - ); - const link = lnik2_1 || lnik2_0 || lnik1_0; - - if (link == null) { - throw new Error("No nodeinfo link provided"); - } - - const info = await getJson(link.href).catch((e) => { - throw new Error(e.statusCode || e.message); - }); - - logger.succ(`Successfuly fetched nodeinfo of ${instance.host}`); - - return info as NodeInfo; - } catch (e) { - logger.error(`Failed to fetch nodeinfo of ${instance.host}: ${e.message}`); - - throw e; - } -} - -async function fetchDom(instance: Instance): Promise<DOMWindow["document"]> { - logger.info(`Fetching HTML of ${instance.host} ...`); - - const url = `https://${instance.host}`; - - const html = await getHtml(url); - - const { window } = new JSDOM(html); - const doc = window.document; - - return doc; -} - -async function fetchManifest( - instance: Instance, -): Promise<Record<string, unknown> | null> { - const url = `https://${instance.host}`; - - const manifestUrl = `${url}/manifest.json`; - - const manifest = (await getJson(manifestUrl)) as Record<string, unknown>; - - return manifest; -} - -async function fetchFaviconUrl( - instance: Instance, - doc: DOMWindow["document"] | null, -): Promise<string | null> { - const url = `https://${instance.host}`; - - if (doc) { - // https://github.com/misskey-dev/misskey/pull/8220#issuecomment-1025104043 - const href = Array.from(doc.getElementsByTagName("link")) - .reverse() - .find((link) => link.relList.contains("icon"))?.href; - - if (href) { - return new URL(href, url).href; - } - } - - const faviconUrl = `${url}/favicon.ico`; - - const favicon = await fetch(faviconUrl, { - // TODO - //timeout: 10000, - agent: getAgentByUrl, - }); - - if (favicon.ok) { - return faviconUrl; - } - - return null; -} - -async function fetchIconUrl( - instance: Instance, - doc: DOMWindow["document"] | null, - manifest: Record<string, any> | null, -): Promise<string | null> { - if (manifest?.icons && manifest.icons.length > 0 && manifest.icons[0].src) { - const url = `https://${instance.host}`; - return new URL(manifest.icons[0].src, url).href; - } - - if (doc) { - const url = `https://${instance.host}`; - - // https://github.com/misskey-dev/misskey/pull/8220#issuecomment-1025104043 - const links = Array.from(doc.getElementsByTagName("link")).reverse(); - // https://github.com/misskey-dev/misskey/pull/8220/files/0ec4eba22a914e31b86874f12448f88b3e58dd5a#r796487559 - const href = [ - links.find((link) => - link.relList.contains("apple-touch-icon-precomposed"), - )?.href, - links.find((link) => link.relList.contains("apple-touch-icon"))?.href, - links.find((link) => link.relList.contains("icon"))?.href, - ].find((href) => href); - - if (href) { - return new URL(href, url).href; - } - } - - return null; -} - -async function getThemeColor( - info: NodeInfo | null, - doc: DOMWindow["document"] | null, - manifest: Record<string, any> | null, -): Promise<string | null> { - const themeColor = - info?.metadata?.themeColor || - doc?.querySelector('meta[name="theme-color"]')?.getAttribute("content") || - manifest?.theme_color; - - if (themeColor) { - const color = new tinycolor(themeColor); - if (color.isValid()) return color.toHexString(); - } - - return null; -} - -async function getSiteName( - info: NodeInfo | null, - doc: DOMWindow["document"] | null, - manifest: Record<string, any> | null, -): Promise<string | null> { - if (info?.metadata) { - if (info.metadata.nodeName || info.metadata.name) { - return info.metadata.nodeName || info.metadata.name; - } - } - - if (doc) { - const og = doc - .querySelector('meta[property="og:title"]') - ?.getAttribute("content"); - - if (og) { - return og; - } - } - - if (manifest) { - return manifest.name || manifest.short_name; - } - - return null; -} - -async function getDescription( - info: NodeInfo | null, - doc: DOMWindow["document"] | null, - manifest: Record<string, any> | null, -): Promise<string | null> { - if (info?.metadata) { - if (info.metadata.nodeDescription || info.metadata.description) { - return info.metadata.nodeDescription || info.metadata.description; - } - } - - if (doc) { - const meta = doc - .querySelector('meta[name="description"]') - ?.getAttribute("content"); - if (meta) { - return meta; - } - - const og = doc - .querySelector('meta[property="og:description"]') - ?.getAttribute("content"); - if (og) { - return og; - } - } - - if (manifest) { - return manifest.name || manifest.short_name; - } - - return null; -} diff --git a/packages/backend/src/services/following/create.ts b/packages/backend/src/services/following/create.ts deleted file mode 100644 index 61a8c6b268..0000000000 --- a/packages/backend/src/services/following/create.ts +++ /dev/null @@ -1,276 +0,0 @@ -import { publishMainStream, publishUserEvent } from "@/services/stream.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import renderFollow from "@/remote/activitypub/renderer/follow.js"; -import renderAccept from "@/remote/activitypub/renderer/accept.js"; -import renderReject from "@/remote/activitypub/renderer/reject.js"; -import { deliver } from "@/queue/index.js"; -import createFollowRequest from "./requests/create.js"; -import { registerOrFetchInstanceDoc } from "../register-or-fetch-instance-doc.js"; -import Logger from "../logger.js"; -import { IdentifiableError } from "@/misc/identifiable-error.js"; -import type { User } from "@/models/entities/user.js"; -import { - Followings, - Users, - FollowRequests, - Blockings, - Instances, - UserProfiles, -} from "@/models/index.js"; -import { - instanceChart, - perUserFollowingChart, -} from "@/services/chart/index.js"; -import { genId } from "@/misc/gen-id.js"; -import { createNotification } from "../create-notification.js"; -import { isDuplicateKeyValueError } from "@/misc/is-duplicate-key-value-error.js"; -import type { Packed } from "@/misc/schema.js"; -import { getActiveWebhooks } from "@/misc/webhook-cache.js"; -import { webhookDeliver } from "@/queue/index.js"; - -const logger = new Logger("following/create"); - -export async function insertFollowingDoc( - followee: { - id: User["id"]; - host: User["host"]; - uri: User["host"]; - inbox: User["inbox"]; - sharedInbox: User["sharedInbox"]; - }, - follower: { - id: User["id"]; - host: User["host"]; - uri: User["host"]; - inbox: User["inbox"]; - sharedInbox: User["sharedInbox"]; - }, -) { - if (follower.id === followee.id) return; - - let alreadyFollowed = false; - - await Followings.insert({ - id: genId(), - createdAt: new Date(), - followerId: follower.id, - followeeId: followee.id, - - // 非正規化 - followerHost: follower.host, - followerInbox: Users.isRemoteUser(follower) ? follower.inbox : null, - followerSharedInbox: Users.isRemoteUser(follower) - ? follower.sharedInbox - : null, - followeeHost: followee.host, - followeeInbox: Users.isRemoteUser(followee) ? followee.inbox : null, - followeeSharedInbox: Users.isRemoteUser(followee) - ? followee.sharedInbox - : null, - }).catch((e) => { - if ( - isDuplicateKeyValueError(e) && - Users.isRemoteUser(follower) && - Users.isLocalUser(followee) - ) { - logger.info(`Insert duplicated ignore. ${follower.id} => ${followee.id}`); - alreadyFollowed = true; - } else { - throw e; - } - }); - - const req = await FollowRequests.findOneBy({ - followeeId: followee.id, - followerId: follower.id, - }); - - if (req) { - await FollowRequests.delete({ - followeeId: followee.id, - followerId: follower.id, - }); - - // Create notification that request was accepted. - createNotification(follower.id, "followRequestAccepted", { - notifierId: followee.id, - }); - } - - if (alreadyFollowed) return; - - //#region Increment counts - await Promise.all([ - Users.increment({ id: follower.id }, "followingCount", 1), - Users.increment({ id: followee.id }, "followersCount", 1), - ]); - //#endregion - - //#region Update instance stats - if (Users.isRemoteUser(follower) && Users.isLocalUser(followee)) { - registerOrFetchInstanceDoc(follower.host).then((i) => { - Instances.increment({ id: i.id }, "followingCount", 1); - instanceChart.updateFollowing(i.host, true); - }); - } else if (Users.isLocalUser(follower) && Users.isRemoteUser(followee)) { - registerOrFetchInstanceDoc(followee.host).then((i) => { - Instances.increment({ id: i.id }, "followersCount", 1); - instanceChart.updateFollowers(i.host, true); - }); - } - //#endregion - - perUserFollowingChart.update(follower, followee, true); - - // Publish follow event - if (Users.isLocalUser(follower)) { - Users.pack(followee.id, follower, { - detail: true, - }).then(async (packed) => { - publishUserEvent( - follower.id, - "follow", - packed as Packed<"UserDetailedNotMe">, - ); - publishMainStream( - follower.id, - "follow", - packed as Packed<"UserDetailedNotMe">, - ); - - const webhooks = (await getActiveWebhooks()).filter( - (x) => x.userId === follower.id && x.on.includes("follow"), - ); - for (const webhook of webhooks) { - webhookDeliver(webhook, "follow", { - user: packed, - }); - } - }); - } - - // Publish followed event - if (Users.isLocalUser(followee)) { - Users.pack(follower.id, followee).then(async (packed) => { - publishMainStream(followee.id, "followed", packed); - - const webhooks = (await getActiveWebhooks()).filter( - (x) => x.userId === followee.id && x.on.includes("followed"), - ); - for (const webhook of webhooks) { - webhookDeliver(webhook, "followed", { - user: packed, - }); - } - }); - - // 通知を作成 - createNotification(followee.id, "follow", { - notifierId: follower.id, - }); - } -} - -export default async function ( - _follower: { id: User["id"] }, - _followee: { id: User["id"] }, - requestId?: string, -) { - const [follower, followee] = await Promise.all([ - Users.findOneByOrFail({ id: _follower.id }), - Users.findOneByOrFail({ id: _followee.id }), - ]); - - // check blocking - const [blocking, blocked] = await Promise.all([ - Blockings.findOneBy({ - blockerId: follower.id, - blockeeId: followee.id, - }), - Blockings.findOneBy({ - blockerId: followee.id, - blockeeId: follower.id, - }), - ]); - - if (Users.isRemoteUser(follower) && Users.isLocalUser(followee) && blocked) { - // リモートフォローを受けてブロックしていた場合は、エラーにするのではなくRejectを送り返しておしまい。 - const content = renderActivity( - renderReject(renderFollow(follower, followee, requestId), followee), - ); - deliver(followee, content, follower.inbox); - return; - } else if ( - Users.isRemoteUser(follower) && - Users.isLocalUser(followee) && - blocking - ) { - // リモートフォローを受けてブロックされているはずの場合だったら、ブロック解除しておく。 - await Blockings.delete(blocking.id); - } else { - // それ以外は単純に例外 - if (blocking) - throw new IdentifiableError( - "710e8fb0-b8c3-4922-be49-d5d93d8e6a6e", - "blocking", - ); - if (blocked) - throw new IdentifiableError( - "3338392a-f764-498d-8855-db939dcf8c48", - "blocked", - ); - } - - const followeeProfile = await UserProfiles.findOneByOrFail({ - userId: followee.id, - }); - - // フォロー対象が鍵アカウントである or - // フォロワーがBotであり、フォロー対象がBotからのフォローに慎重である or - // フォロワーがローカルユーザーであり、フォロー対象がリモートユーザーである - // 上記のいずれかに当てはまる場合はすぐフォローせずにフォローリクエストを発行しておく - if ( - followee.isLocked || - (followeeProfile.carefulBot && follower.isBot) || - (Users.isLocalUser(follower) && Users.isRemoteUser(followee)) - ) { - let autoAccept = false; - - // 鍵アカウントであっても、既にフォローされていた場合はスルー - const following = await Followings.findOneBy({ - followerId: follower.id, - followeeId: followee.id, - }); - if (following) { - autoAccept = true; - } - - // フォローしているユーザーは自動承認オプション - if ( - !autoAccept && - Users.isLocalUser(followee) && - followeeProfile.autoAcceptFollowed - ) { - const followed = await Followings.findOneBy({ - followerId: followee.id, - followeeId: follower.id, - }); - - if (followed) autoAccept = true; - } - - if (!autoAccept) { - await createFollowRequest(follower, followee, requestId); - return; - } - } - - await insertFollowingDoc(followee, follower); - - if (Users.isRemoteUser(follower) && Users.isLocalUser(followee)) { - const content = renderActivity( - renderAccept(renderFollow(follower, followee, requestId), followee), - ); - deliver(followee, content, follower.inbox); - } -} diff --git a/packages/backend/src/services/following/delete.ts b/packages/backend/src/services/following/delete.ts deleted file mode 100644 index fae4bd3cec..0000000000 --- a/packages/backend/src/services/following/delete.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { publishMainStream, publishUserEvent } from "@/services/stream.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import renderFollow from "@/remote/activitypub/renderer/follow.js"; -import renderUndo from "@/remote/activitypub/renderer/undo.js"; -import renderReject from "@/remote/activitypub/renderer/reject.js"; -import { deliver, webhookDeliver } from "@/queue/index.js"; -import Logger from "../logger.js"; -import { registerOrFetchInstanceDoc } from "../register-or-fetch-instance-doc.js"; -import type { User } from "@/models/entities/user.js"; -import { Followings, Users, Instances } from "@/models/index.js"; -import { - instanceChart, - perUserFollowingChart, -} from "@/services/chart/index.js"; -import { getActiveWebhooks } from "@/misc/webhook-cache.js"; - -const logger = new Logger("following/delete"); - -export default async function ( - follower: { - id: User["id"]; - host: User["host"]; - uri: User["host"]; - inbox: User["inbox"]; - sharedInbox: User["sharedInbox"]; - }, - followee: { - id: User["id"]; - host: User["host"]; - uri: User["host"]; - inbox: User["inbox"]; - sharedInbox: User["sharedInbox"]; - }, - silent = false, -) { - const following = await Followings.findOneBy({ - followerId: follower.id, - followeeId: followee.id, - }); - - if (following == null) { - logger.warn( - "フォロー解除がリクエストされましたがフォローしていませんでした", - ); - return; - } - - await Followings.delete(following.id); - - decrementFollowing(follower, followee); - - // Publish unfollow event - if (!silent && Users.isLocalUser(follower)) { - Users.pack(followee.id, follower, { - detail: true, - }).then(async (packed) => { - publishUserEvent(follower.id, "unfollow", packed); - publishMainStream(follower.id, "unfollow", packed); - - const webhooks = (await getActiveWebhooks()).filter( - (x) => x.userId === follower.id && x.on.includes("unfollow"), - ); - for (const webhook of webhooks) { - webhookDeliver(webhook, "unfollow", { - user: packed, - }); - } - }); - } - - if (Users.isLocalUser(follower) && Users.isRemoteUser(followee)) { - const content = renderActivity( - renderUndo(renderFollow(follower, followee), follower), - ); - deliver(follower, content, followee.inbox); - } - - if (Users.isLocalUser(followee) && Users.isRemoteUser(follower)) { - // local user has null host - const content = renderActivity( - renderReject(renderFollow(follower, followee), followee), - ); - deliver(followee, content, follower.inbox); - } -} - -export async function decrementFollowing( - follower: { id: User["id"]; host: User["host"] }, - followee: { id: User["id"]; host: User["host"] }, -) { - //#region Decrement following / followers counts - await Promise.all([ - Users.decrement({ id: follower.id }, "followingCount", 1), - Users.decrement({ id: followee.id }, "followersCount", 1), - ]); - //#endregion - - //#region Update instance stats - if (Users.isRemoteUser(follower) && Users.isLocalUser(followee)) { - registerOrFetchInstanceDoc(follower.host).then((i) => { - Instances.decrement({ id: i.id }, "followingCount", 1); - instanceChart.updateFollowing(i.host, false); - }); - } else if (Users.isLocalUser(follower) && Users.isRemoteUser(followee)) { - registerOrFetchInstanceDoc(followee.host).then((i) => { - Instances.decrement({ id: i.id }, "followersCount", 1); - instanceChart.updateFollowers(i.host, false); - }); - } - //#endregion - - perUserFollowingChart.update(follower, followee, false); -} diff --git a/packages/backend/src/services/following/reject.ts b/packages/backend/src/services/following/reject.ts deleted file mode 100644 index 7464219bf6..0000000000 --- a/packages/backend/src/services/following/reject.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import renderFollow from "@/remote/activitypub/renderer/follow.js"; -import renderReject from "@/remote/activitypub/renderer/reject.js"; -import { deliver, webhookDeliver } from "@/queue/index.js"; -import { publishMainStream, publishUserEvent } from "@/services/stream.js"; -import type { ILocalUser, IRemoteUser } from "@/models/entities/user.js"; -import { User } from "@/models/entities/user.js"; -import { Users, FollowRequests, Followings } from "@/models/index.js"; -import { decrementFollowing } from "./delete.js"; -import { getActiveWebhooks } from "@/misc/webhook-cache.js"; - -type Local = - | ILocalUser - | { - id: ILocalUser["id"]; - host: ILocalUser["host"]; - uri: ILocalUser["uri"]; - }; -type Remote = - | IRemoteUser - | { - id: IRemoteUser["id"]; - host: IRemoteUser["host"]; - uri: IRemoteUser["uri"]; - inbox: IRemoteUser["inbox"]; - }; -type Both = Local | Remote; - -/** - * API following/request/reject - */ -export async function rejectFollowRequest(user: Local, follower: Both) { - if (Users.isRemoteUser(follower)) { - deliverReject(user, follower); - } - - await removeFollowRequest(user, follower); - - if (Users.isLocalUser(follower)) { - publishUnfollow(user, follower); - } -} - -/** - * API following/reject - */ -export async function rejectFollow(user: Local, follower: Both) { - if (Users.isRemoteUser(follower)) { - deliverReject(user, follower); - } - - await removeFollow(user, follower); - - if (Users.isLocalUser(follower)) { - publishUnfollow(user, follower); - } -} - -/** - * AP Reject/Follow - */ -export async function remoteReject(actor: Remote, follower: Local) { - await removeFollowRequest(actor, follower); - await removeFollow(actor, follower); - publishUnfollow(actor, follower); -} - -/** - * Remove follow request record - */ -async function removeFollowRequest(followee: Both, follower: Both) { - const request = await FollowRequests.findOneBy({ - followeeId: followee.id, - followerId: follower.id, - }); - - if (!request) return; - - await FollowRequests.delete(request.id); -} - -/** - * Remove follow record - */ -async function removeFollow(followee: Both, follower: Both) { - const following = await Followings.findOneBy({ - followeeId: followee.id, - followerId: follower.id, - }); - - if (!following) return; - - await Followings.delete(following.id); - decrementFollowing(follower, followee); -} - -/** - * Deliver Reject to remote - */ -async function deliverReject(followee: Local, follower: Remote) { - const request = await FollowRequests.findOneBy({ - followeeId: followee.id, - followerId: follower.id, - }); - - const content = renderActivity( - renderReject( - renderFollow(follower, followee, request?.requestId || undefined), - followee, - ), - ); - deliver(followee, content, follower.inbox); -} - -/** - * Publish unfollow to local - */ -async function publishUnfollow(followee: Both, follower: Local) { - const packedFollowee = await Users.pack(followee.id, follower, { - detail: true, - }); - - publishUserEvent(follower.id, "unfollow", packedFollowee); - publishMainStream(follower.id, "unfollow", packedFollowee); - - const webhooks = (await getActiveWebhooks()).filter( - (x) => x.userId === follower.id && x.on.includes("unfollow"), - ); - for (const webhook of webhooks) { - webhookDeliver(webhook, "unfollow", { - user: packedFollowee, - }); - } -} diff --git a/packages/backend/src/services/following/requests/accept-all.ts b/packages/backend/src/services/following/requests/accept-all.ts deleted file mode 100644 index 2692433799..0000000000 --- a/packages/backend/src/services/following/requests/accept-all.ts +++ /dev/null @@ -1,24 +0,0 @@ -import accept from "./accept.js"; -import type { User } from "@/models/entities/user.js"; -import { FollowRequests, Users } from "@/models/index.js"; - -/** - * Approve all follow requests for the specified user - * @param user User. - */ -export default async function (user: { - id: User["id"]; - host: User["host"]; - uri: User["host"]; - inbox: User["inbox"]; - sharedInbox: User["sharedInbox"]; -}) { - const requests = await FollowRequests.findBy({ - followeeId: user.id, - }); - - for (const request of requests) { - const follower = await Users.findOneByOrFail({ id: request.followerId }); - accept(user, follower); - } -} diff --git a/packages/backend/src/services/following/requests/accept.ts b/packages/backend/src/services/following/requests/accept.ts deleted file mode 100644 index 6aa17b09ad..0000000000 --- a/packages/backend/src/services/following/requests/accept.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import renderFollow from "@/remote/activitypub/renderer/follow.js"; -import renderAccept from "@/remote/activitypub/renderer/accept.js"; -import { deliver } from "@/queue/index.js"; -import { publishMainStream } from "@/services/stream.js"; -import { insertFollowingDoc } from "../create.js"; -import type { User, CacheableUser } from "@/models/entities/user.js"; -import { ILocalUser } from "@/models/entities/user.js"; -import { FollowRequests, Users } from "@/models/index.js"; -import { IdentifiableError } from "@/misc/identifiable-error.js"; - -export default async function ( - followee: { - id: User["id"]; - host: User["host"]; - uri: User["host"]; - inbox: User["inbox"]; - sharedInbox: User["sharedInbox"]; - }, - follower: CacheableUser, -) { - const request = await FollowRequests.findOneBy({ - followeeId: followee.id, - followerId: follower.id, - }); - - if (request == null) { - throw new IdentifiableError( - "8884c2dd-5795-4ac9-b27e-6a01d38190f9", - "No follow request.", - ); - } - - await insertFollowingDoc(followee, follower); - - if (Users.isRemoteUser(follower) && Users.isLocalUser(followee)) { - const content = renderActivity( - renderAccept( - renderFollow(follower, followee, request.requestId!), - followee, - ), - ); - deliver(followee, content, follower.inbox); - } - - Users.pack(followee.id, followee, { - detail: true, - }).then((packed) => publishMainStream(followee.id, "meUpdated", packed)); -} diff --git a/packages/backend/src/services/following/requests/cancel.ts b/packages/backend/src/services/following/requests/cancel.ts deleted file mode 100644 index 00daae380d..0000000000 --- a/packages/backend/src/services/following/requests/cancel.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import renderFollow from "@/remote/activitypub/renderer/follow.js"; -import renderUndo from "@/remote/activitypub/renderer/undo.js"; -import { deliver } from "@/queue/index.js"; -import { publishMainStream } from "@/services/stream.js"; -import { IdentifiableError } from "@/misc/identifiable-error.js"; -import type { User } from "@/models/entities/user.js"; -import { ILocalUser } from "@/models/entities/user.js"; -import { Users, FollowRequests } from "@/models/index.js"; - -export default async function ( - followee: { - id: User["id"]; - host: User["host"]; - uri: User["host"]; - inbox: User["inbox"]; - }, - follower: { id: User["id"]; host: User["host"]; uri: User["host"] }, -) { - if (Users.isRemoteUser(followee)) { - const content = renderActivity( - renderUndo(renderFollow(follower, followee), follower), - ); - - if (Users.isLocalUser(follower)) { - // 本来このチェックは不要だけどTSに怒られるので - deliver(follower, content, followee.inbox); - } - } - - const request = await FollowRequests.findOneBy({ - followeeId: followee.id, - followerId: follower.id, - }); - - if (request == null) { - throw new IdentifiableError( - "17447091-ce07-46dd-b331-c1fd4f15b1e7", - "request not found", - ); - } - - await FollowRequests.delete({ - followeeId: followee.id, - followerId: follower.id, - }); - - Users.pack(followee.id, followee, { - detail: true, - }).then((packed) => publishMainStream(followee.id, "meUpdated", packed)); -} diff --git a/packages/backend/src/services/following/requests/create.ts b/packages/backend/src/services/following/requests/create.ts deleted file mode 100644 index 8b2e86ab5b..0000000000 --- a/packages/backend/src/services/following/requests/create.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { publishMainStream } from "@/services/stream.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import renderFollow from "@/remote/activitypub/renderer/follow.js"; -import { deliver } from "@/queue/index.js"; -import type { User } from "@/models/entities/user.js"; -import { Blockings, FollowRequests, Users } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import { createNotification } from "../../create-notification.js"; - -export default async function ( - follower: { - id: User["id"]; - host: User["host"]; - uri: User["host"]; - inbox: User["inbox"]; - sharedInbox: User["sharedInbox"]; - }, - followee: { - id: User["id"]; - host: User["host"]; - uri: User["host"]; - inbox: User["inbox"]; - sharedInbox: User["sharedInbox"]; - }, - requestId?: string, -) { - if (follower.id === followee.id) return; - - // check blocking - const [blocking, blocked] = await Promise.all([ - Blockings.findOneBy({ - blockerId: follower.id, - blockeeId: followee.id, - }), - Blockings.findOneBy({ - blockerId: followee.id, - blockeeId: follower.id, - }), - ]); - - if (blocking) throw new Error("blocking"); - if (blocked) throw new Error("blocked"); - - const followRequest = await FollowRequests.insert({ - id: genId(), - createdAt: new Date(), - followerId: follower.id, - followeeId: followee.id, - requestId, - - // 非正規化 - followerHost: follower.host, - followerInbox: Users.isRemoteUser(follower) ? follower.inbox : undefined, - followerSharedInbox: Users.isRemoteUser(follower) - ? follower.sharedInbox - : undefined, - followeeHost: followee.host, - followeeInbox: Users.isRemoteUser(followee) ? followee.inbox : undefined, - followeeSharedInbox: Users.isRemoteUser(followee) - ? followee.sharedInbox - : undefined, - }).then((x) => FollowRequests.findOneByOrFail(x.identifiers[0])); - - // Publish receiveRequest event - if (Users.isLocalUser(followee)) { - Users.pack(follower.id, followee).then((packed) => - publishMainStream(followee.id, "receiveFollowRequest", packed), - ); - - Users.pack(followee.id, followee, { - detail: true, - }).then((packed) => publishMainStream(followee.id, "meUpdated", packed)); - - // 通知を作成 - createNotification(followee.id, "receiveFollowRequest", { - notifierId: follower.id, - followRequestId: followRequest.id, - }); - } - - if (Users.isLocalUser(follower) && Users.isRemoteUser(followee)) { - const content = renderActivity(renderFollow(follower, followee)); - deliver(follower, content, followee.inbox); - } -} diff --git a/packages/backend/src/services/i/pin.ts b/packages/backend/src/services/i/pin.ts deleted file mode 100644 index 97045a9fa9..0000000000 --- a/packages/backend/src/services/i/pin.ts +++ /dev/null @@ -1,118 +0,0 @@ -import config from "@/config/index.js"; -import renderAdd from "@/remote/activitypub/renderer/add.js"; -import renderRemove from "@/remote/activitypub/renderer/remove.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import { IdentifiableError } from "@/misc/identifiable-error.js"; -import type { User } from "@/models/entities/user.js"; -import type { Note } from "@/models/entities/note.js"; -import { Notes, UserNotePinings, Users } from "@/models/index.js"; -import type { UserNotePining } from "@/models/entities/user-note-pining.js"; -import { genId } from "@/misc/gen-id.js"; -import { deliverToFollowers } from "@/remote/activitypub/deliver-manager.js"; -import { deliverToRelays } from "../relay.js"; - -/** - * 指定した投稿をピン留めします - * @param user - * @param noteId - */ -export async function addPinned( - user: { id: User["id"]; host: User["host"] }, - noteId: Note["id"], -) { - // Fetch pinee - const note = await Notes.findOneBy({ - id: noteId, - userId: user.id, - }); - - if (note == null) { - throw new IdentifiableError( - "70c4e51f-5bea-449c-a030-53bee3cce202", - "No such note.", - ); - } - - const pinings = await UserNotePinings.findBy({ userId: user.id }); - - if (pinings.length >= 5) { - throw new IdentifiableError( - "15a018eb-58e5-4da1-93be-330fcc5e4e1a", - "You can not pin notes any more.", - ); - } - - if (pinings.some((pining) => pining.noteId === note.id)) { - throw new IdentifiableError( - "23f0cf4e-59a3-4276-a91d-61a5891c1514", - "That note has already been pinned.", - ); - } - - await UserNotePinings.insert({ - id: genId(), - createdAt: new Date(), - userId: user.id, - noteId: note.id, - } as UserNotePining); - - // Deliver to remote followers - if (Users.isLocalUser(user)) { - deliverPinnedChange(user.id, note.id, true); - } -} - -/** - * 指定した投稿のピン留めを解除します - * @param user - * @param noteId - */ -export async function removePinned( - user: { id: User["id"]; host: User["host"] }, - noteId: Note["id"], -) { - // Fetch unpinee - const note = await Notes.findOneBy({ - id: noteId, - userId: user.id, - }); - - if (note == null) { - throw new IdentifiableError( - "b302d4cf-c050-400a-bbb3-be208681f40c", - "No such note.", - ); - } - - UserNotePinings.delete({ - userId: user.id, - noteId: note.id, - }); - - // Deliver to remote followers - if (Users.isLocalUser(user)) { - deliverPinnedChange(user.id, noteId, false); - } -} - -export async function deliverPinnedChange( - userId: User["id"], - noteId: Note["id"], - isAddition: boolean, -) { - const user = await Users.findOneBy({ id: userId }); - if (user == null) throw new Error("user not found"); - - if (!Users.isLocalUser(user)) return; - - const target = `${config.url}/users/${user.id}/collections/featured`; - const item = `${config.url}/notes/${noteId}`; - const content = renderActivity( - isAddition - ? renderAdd(user, target, item) - : renderRemove(user, target, item), - ); - - deliverToFollowers(user, content); - deliverToRelays(user, content); -} diff --git a/packages/backend/src/services/i/update.ts b/packages/backend/src/services/i/update.ts deleted file mode 100644 index cc950ac85a..0000000000 --- a/packages/backend/src/services/i/update.ts +++ /dev/null @@ -1,21 +0,0 @@ -import renderUpdate from "@/remote/activitypub/renderer/update.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import { Users } from "@/models/index.js"; -import type { User } from "@/models/entities/user.js"; -import { renderPerson } from "@/remote/activitypub/renderer/person.js"; -import { deliverToFollowers } from "@/remote/activitypub/deliver-manager.js"; -import { deliverToRelays } from "../relay.js"; - -export async function publishToFollowers(userId: User["id"]) { - const user = await Users.findOneBy({ id: userId }); - if (user == null) throw new Error("user not found"); - - // フォロワーがリモートユーザーかつ投稿者がローカルユーザーならUpdateを配信 - if (Users.isLocalUser(user)) { - const content = renderActivity( - renderUpdate(await renderPerson(user), user), - ); - deliverToFollowers(user, content); - deliverToRelays(user, content); - } -} diff --git a/packages/backend/src/services/insert-moderation-log.ts b/packages/backend/src/services/insert-moderation-log.ts deleted file mode 100644 index 8e2c5b78a1..0000000000 --- a/packages/backend/src/services/insert-moderation-log.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { ModerationLogs } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import type { User } from "@/models/entities/user.js"; - -export async function insertModerationLog( - moderator: { id: User["id"] }, - type: string, - info?: Record<string, any>, -) { - await ModerationLogs.insert({ - id: genId(), - createdAt: new Date(), - userId: moderator.id, - type: type, - info: info || {}, - }); -} diff --git a/packages/backend/src/services/instance-actor.ts b/packages/backend/src/services/instance-actor.ts deleted file mode 100644 index 50ce227eba..0000000000 --- a/packages/backend/src/services/instance-actor.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { createSystemUser } from "./create-system-user.js"; -import type { ILocalUser } from "@/models/entities/user.js"; -import { Users } from "@/models/index.js"; -import { Cache } from "@/misc/cache.js"; -import { IsNull } from "typeorm"; - -const ACTOR_USERNAME = "instance.actor" as const; - -const cache = new Cache<ILocalUser>(Infinity); - -export async function getInstanceActor(): Promise<ILocalUser> { - const cached = cache.get(null); - if (cached) return cached; - - const user = (await Users.findOneBy({ - host: IsNull(), - username: ACTOR_USERNAME, - })) as ILocalUser | undefined; - - if (user) { - cache.set(null, user); - return user; - } else { - const created = (await createSystemUser(ACTOR_USERNAME)) as ILocalUser; - cache.set(null, created); - return created; - } -} diff --git a/packages/backend/src/services/logger.ts b/packages/backend/src/services/logger.ts deleted file mode 100644 index 86e1d10d32..0000000000 --- a/packages/backend/src/services/logger.ts +++ /dev/null @@ -1,199 +0,0 @@ -import cluster from "node:cluster"; -import chalk from "chalk"; -import { default as convertColor } from "color-convert"; -import { format as dateFormat } from "date-fns"; -import { envOption } from "../env.js"; -import config from "@/config/index.js"; - -import * as SyslogPro from "syslog-pro"; - -type Domain = { - name: string; - color?: string; -}; - -type Level = "error" | "success" | "warning" | "debug" | "info"; - -export default class Logger { - private domain: Domain; - private parentLogger: Logger | null = null; - private store: boolean; - private syslogClient: any | null = null; - - constructor(domain: string, color?: string, store = true) { - this.domain = { - name: domain, - color: color, - }; - this.store = store; - - if (config.syslog) { - this.syslogClient = new SyslogPro.RFC5424({ - applacationName: "Calckey", - timestamp: true, - encludeStructuredData: true, - color: true, - extendedColor: true, - server: { - target: config.syslog.host, - port: config.syslog.port, - }, - }); - } - } - - public createSubLogger(domain: string, color?: string, store = true): Logger { - const logger = new Logger(domain, color, store); - logger.parentLogger = this; - return logger; - } - - private log( - level: Level, - message: string, - data?: Record<string, any> | null, - important = false, - subDomains: Domain[] = [], - store = true, - ): void { - if (envOption.quiet) return; - if (!this.store) store = false; - if (level === "debug") store = false; - - if (this.parentLogger) { - this.parentLogger.log( - level, - message, - data, - important, - [this.domain].concat(subDomains), - store, - ); - return; - } - - const time = dateFormat(new Date(), "HH:mm:ss"); - const worker = cluster.isPrimary ? "*" : cluster.worker.id; - const l = - level === "error" - ? important - ? chalk.bgRed.white("ERR ") - : chalk.red("ERR ") - : level === "warning" - ? chalk.yellow("WARN") - : level === "success" - ? important - ? chalk.bgGreen.white("DONE") - : chalk.green("DONE") - : level === "debug" - ? chalk.gray("VERB") - : level === "info" - ? chalk.blue("INFO") - : null; - const domains = [this.domain] - .concat(subDomains) - .map((d) => - d.color - ? chalk.rgb(...convertColor.keyword.rgb(d.color))(d.name) - : chalk.white(d.name), - ); - const m = - level === "error" - ? chalk.red(message) - : level === "warning" - ? chalk.yellow(message) - : level === "success" - ? chalk.green(message) - : level === "debug" - ? chalk.gray(message) - : level === "info" - ? message - : null; - - let log = `${l} ${worker}\t[${domains.join(" ")}]\t${m}`; - if (envOption.withLogTime) log = `${chalk.gray(time)} ${log}`; - - console.log(important ? chalk.bold(log) : log); - - if (store) { - if (this.syslogClient) { - const send = - level === "error" - ? this.syslogClient.error - : level === "warning" - ? this.syslogClient.warning - : level === "success" - ? this.syslogClient.info - : level === "debug" - ? this.syslogClient.info - : level === "info" - ? this.syslogClient.info - : (null as never); - - send - .bind(this.syslogClient)(message) - .catch(() => {}); - } - } - } - - public error( - x: string | Error, - data?: Record<string, any> | null, - important = false, - ): void { - // 実行を継続できない状況で使う - if (x instanceof Error) { - data = data || {}; - data.e = x; - this.log("error", x.toString(), data, important); - } else if (typeof x === "object") { - this.log( - "error", - `${(x as any).message || (x as any).name || x}`, - data, - important, - ); - } else { - this.log("error", `${x}`, data, important); - } - } - - public warn( - message: string, - data?: Record<string, any> | null, - important = false, - ): void { - // 実行を継続できるが改善すべき状況で使う - this.log("warning", message, data, important); - } - - public succ( - message: string, - data?: Record<string, any> | null, - important = false, - ): void { - // 何かに成功した状況で使う - this.log("success", message, data, important); - } - - public debug( - message: string, - data?: Record<string, any> | null, - important = false, - ): void { - // デバッグ用に使う(開発者に必要だが利用者に不要な情報) - if (process.env.NODE_ENV !== "production" || envOption.verbose) { - this.log("debug", message, data, important); - } - } - - public info( - message: string, - data?: Record<string, any> | null, - important = false, - ): void { - // それ以外 - this.log("info", message, data, important); - } -} diff --git a/packages/backend/src/services/messages/create.ts b/packages/backend/src/services/messages/create.ts deleted file mode 100644 index 506f299966..0000000000 --- a/packages/backend/src/services/messages/create.ts +++ /dev/null @@ -1,148 +0,0 @@ -import type { CacheableUser, User } from "@/models/entities/user.js"; -import type { UserGroup } from "@/models/entities/user-group.js"; -import type { DriveFile } from "@/models/entities/drive-file.js"; -import { - MessagingMessages, - UserGroupJoinings, - Mutings, - Users, -} from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import type { MessagingMessage } from "@/models/entities/messaging-message.js"; -import { - publishMessagingStream, - publishMessagingIndexStream, - publishMainStream, - publishGroupMessagingStream, -} from "@/services/stream.js"; -import { pushNotification } from "@/services/push-notification.js"; -import { Not } from "typeorm"; -import type { Note } from "@/models/entities/note.js"; -import renderNote from "@/remote/activitypub/renderer/note.js"; -import renderCreate from "@/remote/activitypub/renderer/create.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import { deliver } from "@/queue/index.js"; - -export async function createMessage( - user: { id: User["id"]; host: User["host"] }, - recipientUser: CacheableUser | undefined, - recipientGroup: UserGroup | undefined, - text: string | null | undefined, - file: DriveFile | null, - uri?: string, -) { - const message = { - id: genId(), - createdAt: new Date(), - fileId: file ? file.id : null, - recipientId: recipientUser ? recipientUser.id : null, - groupId: recipientGroup ? recipientGroup.id : null, - text: text ? text.trim() : null, - userId: user.id, - isRead: false, - reads: [] as any[], - uri, - } as MessagingMessage; - - await MessagingMessages.insert(message); - - const messageObj = await MessagingMessages.pack(message); - - if (recipientUser) { - if (Users.isLocalUser(user)) { - // 自分のストリーム - publishMessagingStream( - message.userId, - recipientUser.id, - "message", - messageObj, - ); - publishMessagingIndexStream(message.userId, "message", messageObj); - publishMainStream(message.userId, "messagingMessage", messageObj); - } - - if (Users.isLocalUser(recipientUser)) { - // 相手のストリーム - publishMessagingStream( - recipientUser.id, - message.userId, - "message", - messageObj, - ); - publishMessagingIndexStream(recipientUser.id, "message", messageObj); - publishMainStream(recipientUser.id, "messagingMessage", messageObj); - } - } else if (recipientGroup) { - // グループのストリーム - publishGroupMessagingStream(recipientGroup.id, "message", messageObj); - - // メンバーのストリーム - const joinings = await UserGroupJoinings.findBy({ - userGroupId: recipientGroup.id, - }); - for (const joining of joinings) { - publishMessagingIndexStream(joining.userId, "message", messageObj); - publishMainStream(joining.userId, "messagingMessage", messageObj); - } - } - - // 2秒経っても(今回作成した)メッセージが既読にならなかったら「未読のメッセージがありますよ」イベントを発行する - setTimeout(async () => { - const freshMessage = await MessagingMessages.findOneBy({ id: message.id }); - if (freshMessage == null) return; // メッセージが削除されている場合もある - - if (recipientUser && Users.isLocalUser(recipientUser)) { - if (freshMessage.isRead) return; // 既読 - - //#region ただしミュートされているなら発行しない - const mute = await Mutings.findBy({ - muterId: recipientUser.id, - }); - if (mute.map((m) => m.muteeId).includes(user.id)) return; - //#endregion - - publishMainStream(recipientUser.id, "unreadMessagingMessage", messageObj); - pushNotification(recipientUser.id, "unreadMessagingMessage", messageObj); - } else if (recipientGroup) { - const joinings = await UserGroupJoinings.findBy({ - userGroupId: recipientGroup.id, - userId: Not(user.id), - }); - for (const joining of joinings) { - if (freshMessage.reads.includes(joining.userId)) return; // 既読 - publishMainStream(joining.userId, "unreadMessagingMessage", messageObj); - pushNotification(joining.userId, "unreadMessagingMessage", messageObj); - } - } - }, 2000); - - if ( - recipientUser && - Users.isLocalUser(user) && - Users.isRemoteUser(recipientUser) - ) { - const note = { - id: message.id, - createdAt: message.createdAt, - fileIds: message.fileId ? [message.fileId] : [], - text: message.text, - userId: message.userId, - visibility: "specified", - mentions: [recipientUser].map((u) => u.id), - mentionedRemoteUsers: JSON.stringify( - [recipientUser].map((u) => ({ - uri: u.uri, - username: u.username, - host: u.host, - })), - ), - } as Note; - - const activity = renderActivity( - renderCreate(await renderNote(note, false, true), note), - ); - - deliver(user, activity, recipientUser.inbox); - } - return messageObj; -} diff --git a/packages/backend/src/services/messages/delete.ts b/packages/backend/src/services/messages/delete.ts deleted file mode 100644 index 77caba80ce..0000000000 --- a/packages/backend/src/services/messages/delete.ts +++ /dev/null @@ -1,50 +0,0 @@ -import config from "@/config/index.js"; -import { MessagingMessages, Users } from "@/models/index.js"; -import type { MessagingMessage } from "@/models/entities/messaging-message.js"; -import { - publishGroupMessagingStream, - publishMessagingStream, -} from "@/services/stream.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import renderDelete from "@/remote/activitypub/renderer/delete.js"; -import renderTombstone from "@/remote/activitypub/renderer/tombstone.js"; -import { deliver } from "@/queue/index.js"; - -export async function deleteMessage(message: MessagingMessage) { - await MessagingMessages.delete(message.id); - postDeleteMessage(message); -} - -async function postDeleteMessage(message: MessagingMessage) { - if (message.recipientId) { - const user = await Users.findOneByOrFail({ id: message.userId }); - const recipient = await Users.findOneByOrFail({ id: message.recipientId }); - - if (Users.isLocalUser(user)) - publishMessagingStream( - message.userId, - message.recipientId, - "deleted", - message.id, - ); - if (Users.isLocalUser(recipient)) - publishMessagingStream( - message.recipientId, - message.userId, - "deleted", - message.id, - ); - - if (Users.isLocalUser(user) && Users.isRemoteUser(recipient)) { - const activity = renderActivity( - renderDelete( - renderTombstone(`${config.url}/notes/${message.id}`), - user, - ), - ); - deliver(user, activity, recipient.inbox); - } - } else if (message.groupId) { - publishGroupMessagingStream(message.groupId, "deleted", message.id); - } -} diff --git a/packages/backend/src/services/note/create.ts b/packages/backend/src/services/note/create.ts deleted file mode 100644 index 5dd324d89a..0000000000 --- a/packages/backend/src/services/note/create.ts +++ /dev/null @@ -1,871 +0,0 @@ -import * as mfm from "mfm-js"; -import es from "../../db/elasticsearch.js"; -import sonic from "../../db/sonic.js"; -import { - publishMainStream, - publishNotesStream, - publishNoteStream, -} from "@/services/stream.js"; -import DeliverManager from "@/remote/activitypub/deliver-manager.js"; -import renderNote from "@/remote/activitypub/renderer/note.js"; -import renderCreate from "@/remote/activitypub/renderer/create.js"; -import renderAnnounce from "@/remote/activitypub/renderer/announce.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import { resolveUser } from "@/remote/resolve-user.js"; -import config from "@/config/index.js"; -import { updateHashtags } from "../update-hashtag.js"; -import { concat } from "@/prelude/array.js"; -import { insertNoteUnread } from "@/services/note/unread.js"; -import { registerOrFetchInstanceDoc } from "../register-or-fetch-instance-doc.js"; -import { extractMentions } from "@/misc/extract-mentions.js"; -import { extractCustomEmojisFromMfm } from "@/misc/extract-custom-emojis-from-mfm.js"; -import { extractHashtags } from "@/misc/extract-hashtags.js"; -import type { IMentionedRemoteUsers } from "@/models/entities/note.js"; -import { Note } from "@/models/entities/note.js"; -import { - Mutings, - Users, - NoteWatchings, - Notes, - Instances, - UserProfiles, - Antennas, - Followings, - MutedNotes, - Channels, - ChannelFollowings, - Blockings, - NoteThreadMutings, -} from "@/models/index.js"; -import type { DriveFile } from "@/models/entities/drive-file.js"; -import type { App } from "@/models/entities/app.js"; -import { Not, In } from "typeorm"; -import type { User, ILocalUser, IRemoteUser } from "@/models/entities/user.js"; -import { genId } from "@/misc/gen-id.js"; -import { - notesChart, - perUserNotesChart, - activeUsersChart, - instanceChart, -} from "@/services/chart/index.js"; -import type { IPoll } from "@/models/entities/poll.js"; -import { Poll } from "@/models/entities/poll.js"; -import { createNotification } from "../create-notification.js"; -import { isDuplicateKeyValueError } from "@/misc/is-duplicate-key-value-error.js"; -import { checkHitAntenna } from "@/misc/check-hit-antenna.js"; -import { getWordMute } from "@/misc/check-word-mute.js"; -import { addNoteToAntenna } from "../add-note-to-antenna.js"; -import { countSameRenotes } from "@/misc/count-same-renotes.js"; -import { deliverToRelays } from "../relay.js"; -import type { Channel } from "@/models/entities/channel.js"; -import { normalizeForSearch } from "@/misc/normalize-for-search.js"; -import { getAntennas } from "@/misc/antenna-cache.js"; -import { endedPollNotificationQueue } from "@/queue/queues.js"; -import { webhookDeliver } from "@/queue/index.js"; -import { Cache } from "@/misc/cache.js"; -import type { UserProfile } from "@/models/entities/user-profile.js"; -import { db } from "@/db/postgre.js"; -import { getActiveWebhooks } from "@/misc/webhook-cache.js"; - -const mutedWordsCache = new Cache< - { userId: UserProfile["userId"]; mutedWords: UserProfile["mutedWords"] }[] ->(1000 * 60 * 5); - -type NotificationType = "reply" | "renote" | "quote" | "mention"; - -class NotificationManager { - private notifier: { id: User["id"] }; - private note: Note; - private queue: { - target: ILocalUser["id"]; - reason: NotificationType; - }[]; - - constructor(notifier: { id: User["id"] }, note: Note) { - this.notifier = notifier; - this.note = note; - this.queue = []; - } - - public push(notifiee: ILocalUser["id"], reason: NotificationType) { - // 自分自身へは通知しない - if (this.notifier.id === notifiee) return; - - const exist = this.queue.find((x) => x.target === notifiee); - - if (exist) { - // 「メンションされているかつ返信されている」場合は、メンションとしての通知ではなく返信としての通知にする - if (reason !== "mention") { - exist.reason = reason; - } - } else { - this.queue.push({ - reason: reason, - target: notifiee, - }); - } - } - - public async deliver() { - for (const x of this.queue) { - // ミュート情報を取得 - const mentioneeMutes = await Mutings.findBy({ - muterId: x.target, - }); - - const mentioneesMutedUserIds = mentioneeMutes.map((m) => m.muteeId); - - // 通知される側のユーザーが通知する側のユーザーをミュートしていない限りは通知する - if (!mentioneesMutedUserIds.includes(this.notifier.id)) { - createNotification(x.target, x.reason, { - notifierId: this.notifier.id, - noteId: this.note.id, - note: this.note, - }); - } - } - } -} - -type MinimumUser = { - id: User["id"]; - host: User["host"]; - username: User["username"]; - uri: User["uri"]; -}; - -type Option = { - createdAt?: Date | null; - name?: string | null; - text?: string | null; - reply?: Note | null; - renote?: Note | null; - files?: DriveFile[] | null; - poll?: IPoll | null; - localOnly?: boolean | null; - cw?: string | null; - visibility?: string; - visibleUsers?: MinimumUser[] | null; - channel?: Channel | null; - apMentions?: MinimumUser[] | null; - apHashtags?: string[] | null; - apEmojis?: string[] | null; - uri?: string | null; - url?: string | null; - app?: App | null; -}; - -export default async ( - user: { - id: User["id"]; - username: User["username"]; - host: User["host"]; - isSilenced: User["isSilenced"]; - createdAt: User["createdAt"]; - }, - data: Option, - silent = false, -) => - new Promise<Note>(async (res, rej) => { - // If you reply outside the channel, match the scope of the target. - // TODO (I think it's a process that could be done on the client side, but it's server side for now.) - if ( - data.reply && - data.channel && - data.reply.channelId !== data.channel.id - ) { - if (data.reply.channelId) { - data.channel = await Channels.findOneBy({ id: data.reply.channelId }); - } else { - data.channel = null; - } - } - - // When you reply in a channel, match the scope of the target - // TODO (I think it's a process that could be done on the client side, but it's server side for now.) - if (data.reply && data.channel == null && data.reply.channelId) { - data.channel = await Channels.findOneBy({ id: data.reply.channelId }); - } - - if (data.createdAt == null) data.createdAt = new Date(); - if (data.visibility == null) data.visibility = "public"; - if (data.localOnly == null) data.localOnly = false; - if (data.channel != null) data.visibility = "public"; - if (data.channel != null) data.visibleUsers = []; - if (data.channel != null) data.localOnly = true; - - // enforce silent clients on server - if ( - user.isSilenced && - data.visibility === "public" && - data.channel == null - ) { - data.visibility = "home"; - } - - // Reject if the target of the renote is a public range other than "Home or Entire". - if ( - data.renote && - data.renote.visibility !== "public" && - data.renote.visibility !== "home" && - data.renote.userId !== user.id - ) { - return rej("Renote target is not public or home"); - } - - // If the target of the renote is not public, make it home. - if ( - data.renote && - data.renote.visibility !== "public" && - data.visibility === "public" - ) { - data.visibility = "home"; - } - - // If the target of Renote is followers, make it followers. - if (data.renote && data.renote.visibility === "followers") { - data.visibility = "followers"; - } - - // If the reply target is not public, make it home. - if ( - data.reply && - data.reply.visibility !== "public" && - data.visibility === "public" - ) { - data.visibility = "home"; - } - - // Renote local only if you Renote local only. - if (data.renote?.localOnly && data.channel == null) { - data.localOnly = true; - } - - // If you reply to local only, make it local only. - if (data.reply?.localOnly && data.channel == null) { - data.localOnly = true; - } - - if (data.text) { - data.text = data.text.trim(); - } else { - data.text = null; - } - - let tags = data.apHashtags; - let emojis = data.apEmojis; - let mentionedUsers = data.apMentions; - - // Parse MFM if needed - if (!(tags && emojis && mentionedUsers)) { - const tokens = data.text ? mfm.parse(data.text)! : []; - const cwTokens = data.cw ? mfm.parse(data.cw)! : []; - const choiceTokens = data.poll?.choices - ? concat(data.poll.choices.map((choice) => mfm.parse(choice)!)) - : []; - - const combinedTokens = tokens.concat(cwTokens).concat(choiceTokens); - - tags = data.apHashtags || extractHashtags(combinedTokens); - - emojis = data.apEmojis || extractCustomEmojisFromMfm(combinedTokens); - - mentionedUsers = - data.apMentions || (await extractMentionedUsers(user, combinedTokens)); - } - - tags = tags - .filter((tag) => Array.from(tag || "").length <= 128) - .splice(0, 32); - - if ( - data.reply && - user.id !== data.reply.userId && - !mentionedUsers.some((u) => u.id === data.reply!.userId) - ) { - mentionedUsers.push( - await Users.findOneByOrFail({ id: data.reply!.userId }), - ); - } - - if (data.visibility === "specified") { - if (data.visibleUsers == null) throw new Error("invalid param"); - - for (const u of data.visibleUsers) { - if (!mentionedUsers.some((x) => x.id === u.id)) { - mentionedUsers.push(u); - } - } - - if ( - data.reply && - !data.visibleUsers.some((x) => x.id === data.reply!.userId) - ) { - data.visibleUsers.push( - await Users.findOneByOrFail({ id: data.reply!.userId }), - ); - } - } - - const note = await insertNote(user, data, tags, emojis, mentionedUsers); - - res(note); - - // 統計を更新 - notesChart.update(note, true); - perUserNotesChart.update(user, note, true); - - // Register host - if (Users.isRemoteUser(user)) { - registerOrFetchInstanceDoc(user.host).then((i) => { - Instances.increment({ id: i.id }, "notesCount", 1); - instanceChart.updateNote(i.host, note, true); - }); - } - - // ハッシュタグ更新 - if (data.visibility === "public" || data.visibility === "home") { - updateHashtags(user, tags); - } - - // Increment notes count (user) - incNotesCountOfUser(user); - - // Word mute - mutedWordsCache - .fetch(null, () => - UserProfiles.find({ - where: { - enableWordMute: true, - }, - select: ["userId", "mutedWords"], - }), - ) - .then((us) => { - for (const u of us) { - getWordMute(note, { id: u.userId }, u.mutedWords).then( - (shouldMute) => { - if (shouldMute.muted) { - MutedNotes.insert({ - id: genId(), - userId: u.userId, - noteId: note.id, - reason: "word", - }); - } - }, - ); - } - }); - - // Antenna - for (const antenna of await getAntennas()) { - checkHitAntenna(antenna, note, user).then((hit) => { - if (hit) { - addNoteToAntenna(antenna, note, user); - } - }); - } - - // Channel - if (note.channelId) { - ChannelFollowings.findBy({ followeeId: note.channelId }).then( - (followings) => { - for (const following of followings) { - insertNoteUnread(following.followerId, note, { - isSpecified: false, - isMentioned: false, - }); - } - }, - ); - } - - if (data.reply) { - saveReply(data.reply, note); - } - - // この投稿を除く指定したユーザーによる指定したノートのリノートが存在しないとき - if ( - data.renote && - (await countSameRenotes(user.id, data.renote.id, note.id)) === 0 - ) { - incRenoteCount(data.renote); - } - - if (data.poll?.expiresAt) { - const delay = data.poll.expiresAt.getTime() - Date.now(); - endedPollNotificationQueue.add( - { - noteId: note.id, - }, - { - delay, - removeOnComplete: true, - }, - ); - } - - if (!silent) { - if (Users.isLocalUser(user)) activeUsersChart.write(user); - - // 未読通知を作成 - if (data.visibility === "specified") { - if (data.visibleUsers == null) throw new Error("invalid param"); - - for (const u of data.visibleUsers) { - // ローカルユーザーのみ - if (!Users.isLocalUser(u)) continue; - - insertNoteUnread(u.id, note, { - isSpecified: true, - isMentioned: false, - }); - } - } else { - for (const u of mentionedUsers) { - // ローカルユーザーのみ - if (!Users.isLocalUser(u)) continue; - - insertNoteUnread(u.id, note, { - isSpecified: false, - isMentioned: true, - }); - } - } - - publishNotesStream(note); - if (note.replyId != null) { - // Only provide the reply note id here as the recipient may not be authorized to see the note. - publishNoteStream(note.replyId, "replied", { - id: note.id, - }); - } - - const webhooks = await getActiveWebhooks().then((webhooks) => - webhooks.filter((x) => x.userId === user.id && x.on.includes("note")), - ); - - for (const webhook of webhooks) { - webhookDeliver(webhook, "note", { - note: await Notes.pack(note, user), - }); - } - - const nm = new NotificationManager(user, note); - const nmRelatedPromises = []; - - await createMentionedEvents(mentionedUsers, note, nm); - - // If has in reply to note - if (data.reply) { - // Fetch watchers - nmRelatedPromises.push(notifyToWatchersOfReplyee(data.reply, user, nm)); - - // 通知 - if (data.reply.userHost === null) { - const threadMuted = await NoteThreadMutings.findOneBy({ - userId: data.reply.userId, - threadId: data.reply.threadId || data.reply.id, - }); - - if (!threadMuted) { - nm.push(data.reply.userId, "reply"); - - const packedReply = await Notes.pack(note, { - id: data.reply.userId, - }); - publishMainStream(data.reply.userId, "reply", packedReply); - - const webhooks = (await getActiveWebhooks()).filter( - (x) => x.userId === data.reply!.userId && x.on.includes("reply"), - ); - for (const webhook of webhooks) { - webhookDeliver(webhook, "reply", { - note: packedReply, - }); - } - } - } - } - - // If it is renote - if (data.renote) { - const type = data.text ? "quote" : "renote"; - - // Notify - if (data.renote.userHost === null) { - const threadMuted = await NoteThreadMutings.findOneBy({ - userId: data.renote.userId, - threadId: data.renote.threadId || data.renote.id, - }); - - if (!threadMuted) { - nm.push(data.renote.userId, type); - } - } - - // Fetch watchers - nmRelatedPromises.push( - notifyToWatchersOfRenotee(data.renote, user, nm, type), - ); - - // Publish event - if (user.id !== data.renote.userId && data.renote.userHost === null) { - const packedRenote = await Notes.pack(note, { - id: data.renote.userId, - }); - publishMainStream(data.renote.userId, "renote", packedRenote); - - const webhooks = (await getActiveWebhooks()).filter( - (x) => x.userId === data.renote!.userId && x.on.includes("renote"), - ); - for (const webhook of webhooks) { - webhookDeliver(webhook, "renote", { - note: packedRenote, - }); - } - } - } - - Promise.all(nmRelatedPromises).then(() => { - nm.deliver(); - }); - - //#region AP deliver - if (Users.isLocalUser(user)) { - (async () => { - const noteActivity = await renderNoteOrRenoteActivity(data, note); - const dm = new DeliverManager(user, noteActivity); - - // メンションされたリモートユーザーに配送 - for (const u of mentionedUsers.filter((u) => Users.isRemoteUser(u))) { - dm.addDirectRecipe(u as IRemoteUser); - } - - // 投稿がリプライかつ投稿者がローカルユーザーかつリプライ先の投稿の投稿者がリモートユーザーなら配送 - if (data.reply && data.reply.userHost !== null) { - const u = await Users.findOneBy({ id: data.reply.userId }); - if (u && Users.isRemoteUser(u)) dm.addDirectRecipe(u); - } - - // 投稿がRenoteかつ投稿者がローカルユーザーかつRenote元の投稿の投稿者がリモートユーザーなら配送 - if (data.renote && data.renote.userHost !== null) { - const u = await Users.findOneBy({ id: data.renote.userId }); - if (u && Users.isRemoteUser(u)) dm.addDirectRecipe(u); - } - - // フォロワーに配送 - if (["public", "home", "followers"].includes(note.visibility)) { - dm.addFollowersRecipe(); - } - - if (["public"].includes(note.visibility)) { - deliverToRelays(user, noteActivity); - } - - dm.execute(); - })(); - } - //#endregion - } - - if (data.channel) { - Channels.increment({ id: data.channel.id }, "notesCount", 1); - Channels.update(data.channel.id, { - lastNotedAt: new Date(), - }); - - const count = await Notes.countBy({ - userId: user.id, - channelId: data.channel.id, - }).then((count) => { - // この処理が行われるのはノート作成後なので、ノートが一つしかなかったら最初の投稿だと判断できる - // TODO: とはいえノートを削除して何回も投稿すればその分だけインクリメントされる雑さもあるのでどうにかしたい - if (count === 1) { - Channels.increment({ id: data.channel!.id }, "usersCount", 1); - } - }); - } - - // Register to search database - await index(note); - }); - -async function renderNoteOrRenoteActivity(data: Option, note: Note) { - if (data.localOnly) return null; - - const content = - data.renote && - data.text == null && - data.poll == null && - (data.files == null || data.files.length === 0) - ? renderAnnounce( - data.renote.uri - ? data.renote.uri - : `${config.url}/notes/${data.renote.id}`, - note, - ) - : renderCreate(await renderNote(note, false), note); - - return renderActivity(content); -} - -function incRenoteCount(renote: Note) { - Notes.createQueryBuilder() - .update() - .set({ - renoteCount: () => '"renoteCount" + 1', - score: () => '"score" + 1', - }) - .where("id = :id", { id: renote.id }) - .execute(); -} - -async function insertNote( - user: { id: User["id"]; host: User["host"] }, - data: Option, - tags: string[], - emojis: string[], - mentionedUsers: MinimumUser[], -) { - const insert = new Note({ - id: genId(data.createdAt!), - createdAt: data.createdAt!, - fileIds: data.files ? data.files.map((file) => file.id) : [], - replyId: data.reply ? data.reply.id : null, - renoteId: data.renote ? data.renote.id : null, - channelId: data.channel ? data.channel.id : null, - threadId: data.reply - ? data.reply.threadId - ? data.reply.threadId - : data.reply.id - : null, - name: data.name, - text: data.text, - hasPoll: data.poll != null, - cw: data.cw == null ? null : data.cw, - tags: tags.map((tag) => normalizeForSearch(tag)), - emojis, - userId: user.id, - localOnly: data.localOnly!, - visibility: data.visibility as any, - visibleUserIds: - data.visibility === "specified" - ? data.visibleUsers - ? data.visibleUsers.map((u) => u.id) - : [] - : [], - - attachedFileTypes: data.files ? data.files.map((file) => file.type) : [], - - // 以下非正規化データ - replyUserId: data.reply ? data.reply.userId : null, - replyUserHost: data.reply ? data.reply.userHost : null, - renoteUserId: data.renote ? data.renote.userId : null, - renoteUserHost: data.renote ? data.renote.userHost : null, - userHost: user.host, - }); - - if (data.uri != null) insert.uri = data.uri; - if (data.url != null) insert.url = data.url; - - // Append mentions data - if (mentionedUsers.length > 0) { - insert.mentions = mentionedUsers.map((u) => u.id); - const profiles = await UserProfiles.findBy({ userId: In(insert.mentions) }); - insert.mentionedRemoteUsers = JSON.stringify( - mentionedUsers - .filter((u) => Users.isRemoteUser(u)) - .map((u) => { - const profile = profiles.find((p) => p.userId === u.id); - const url = profile != null ? profile.url : null; - return { - uri: u.uri, - url: url == null ? undefined : url, - username: u.username, - host: u.host, - } as IMentionedRemoteUsers[0]; - }), - ); - } - - // 投稿を作成 - try { - if (insert.hasPoll) { - // Start transaction - await db.transaction(async (transactionalEntityManager) => { - await transactionalEntityManager.insert(Note, insert); - - const poll = new Poll({ - noteId: insert.id, - choices: data.poll!.choices, - expiresAt: data.poll!.expiresAt, - multiple: data.poll!.multiple, - votes: new Array(data.poll!.choices.length).fill(0), - noteVisibility: insert.visibility, - userId: user.id, - userHost: user.host, - }); - - await transactionalEntityManager.insert(Poll, poll); - }); - } else { - await Notes.insert(insert); - } - - return insert; - } catch (e) { - // duplicate key error - if (isDuplicateKeyValueError(e)) { - const err = new Error("Duplicated note"); - err.name = "duplicated"; - throw err; - } - - console.error(e); - - throw e; - } -} - -export async function index(note: Note): Promise<void> { - if (!note.text) return; - - if (config.elasticsearch && es) { - es.index({ - index: config.elasticsearch.index || "misskey_note", - id: note.id.toString(), - body: { - text: normalizeForSearch(note.text), - userId: note.userId, - userHost: note.userHost, - }, - }); - } - - if (sonic) { - await sonic.ingest.push( - sonic.collection, - sonic.bucket, - JSON.stringify({ - id: note.id, - userId: note.userId, - userHost: note.userHost, - channelId: note.channelId, - }), - note.text, - ); - } -} - -async function notifyToWatchersOfRenotee( - renote: Note, - user: { id: User["id"] }, - nm: NotificationManager, - type: NotificationType, -) { - const watchers = await NoteWatchings.findBy({ - noteId: renote.id, - userId: Not(user.id), - }); - - for (const watcher of watchers) { - nm.push(watcher.userId, type); - } -} - -async function notifyToWatchersOfReplyee( - reply: Note, - user: { id: User["id"] }, - nm: NotificationManager, -) { - const watchers = await NoteWatchings.findBy({ - noteId: reply.id, - userId: Not(user.id), - }); - - for (const watcher of watchers) { - nm.push(watcher.userId, "reply"); - } -} - -async function createMentionedEvents( - mentionedUsers: MinimumUser[], - note: Note, - nm: NotificationManager, -) { - for (const u of mentionedUsers.filter((u) => Users.isLocalUser(u))) { - const threadMuted = await NoteThreadMutings.findOneBy({ - userId: u.id, - threadId: note.threadId || note.id, - }); - - if (threadMuted) { - continue; - } - - // note with "specified" visibility might not be visible to mentioned users - try { - const detailPackedNote = await Notes.pack(note, u, { - detail: true, - }); - - publishMainStream(u.id, "mention", detailPackedNote); - - const webhooks = (await getActiveWebhooks()).filter( - (x) => x.userId === u.id && x.on.includes("mention"), - ); - for (const webhook of webhooks) { - webhookDeliver(webhook, "mention", { - note: detailPackedNote, - }); - } - } catch (err) { - if (err.id === "9725d0ce-ba28-4dde-95a7-2cbb2c15de24") continue; - throw err; - } - - // Create notification - nm.push(u.id, "mention"); - } -} - -function saveReply(reply: Note, note: Note) { - Notes.increment({ id: reply.id }, "repliesCount", 1); -} - -function incNotesCountOfUser(user: { id: User["id"] }) { - Users.createQueryBuilder() - .update() - .set({ - updatedAt: new Date(), - notesCount: () => '"notesCount" + 1', - }) - .where("id = :id", { id: user.id }) - .execute(); -} - -async function extractMentionedUsers( - user: { host: User["host"] }, - tokens: mfm.MfmNode[], -): Promise<User[]> { - if (tokens == null) return []; - - const mentions = extractMentions(tokens); - - let mentionedUsers = ( - await Promise.all( - mentions.map((m) => - resolveUser(m.username, m.host || user.host).catch(() => null), - ), - ) - ).filter((x) => x != null) as User[]; - - // Drop duplicate users - mentionedUsers = mentionedUsers.filter( - (u, i, self) => i === self.findIndex((u2) => u.id === u2.id), - ); - - return mentionedUsers; -} diff --git a/packages/backend/src/services/note/delete.ts b/packages/backend/src/services/note/delete.ts deleted file mode 100644 index 392578e2f6..0000000000 --- a/packages/backend/src/services/note/delete.ts +++ /dev/null @@ -1,185 +0,0 @@ -import { Brackets, In } from "typeorm"; -import { publishNoteStream } from "@/services/stream.js"; -import renderDelete from "@/remote/activitypub/renderer/delete.js"; -import renderAnnounce from "@/remote/activitypub/renderer/announce.js"; -import renderUndo from "@/remote/activitypub/renderer/undo.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import renderTombstone from "@/remote/activitypub/renderer/tombstone.js"; -import config from "@/config/index.js"; -import type { User, ILocalUser, IRemoteUser } from "@/models/entities/user.js"; -import type { Note, IMentionedRemoteUsers } from "@/models/entities/note.js"; -import { Notes, Users, Instances } from "@/models/index.js"; -import { - notesChart, - perUserNotesChart, - instanceChart, -} from "@/services/chart/index.js"; -import { - deliverToFollowers, - deliverToUser, -} from "@/remote/activitypub/deliver-manager.js"; -import { countSameRenotes } from "@/misc/count-same-renotes.js"; -import { registerOrFetchInstanceDoc } from "../register-or-fetch-instance-doc.js"; -import { deliverToRelays } from "../relay.js"; - -/** - * 投稿を削除します。 - * @param user 投稿者 - * @param note 投稿 - */ -export default async function ( - user: { id: User["id"]; uri: User["uri"]; host: User["host"] }, - note: Note, - quiet = false, -) { - const deletedAt = new Date(); - - // この投稿を除く指定したユーザーによる指定したノートのリノートが存在しないとき - if ( - note.renoteId && - (await countSameRenotes(user.id, note.renoteId, note.id)) === 0 - ) { - Notes.decrement({ id: note.renoteId }, "renoteCount", 1); - Notes.decrement({ id: note.renoteId }, "score", 1); - } - - if (note.replyId) { - await Notes.decrement({ id: note.replyId }, "repliesCount", 1); - } - - if (!quiet) { - publishNoteStream(note.id, "deleted", { - deletedAt: deletedAt, - }); - - //#region ローカルの投稿なら削除アクティビティを配送 - if (Users.isLocalUser(user) && !note.localOnly) { - let renote: Note | null = null; - - // if deletd note is renote - if ( - note.renoteId && - note.text == null && - !note.hasPoll && - (note.fileIds == null || note.fileIds.length === 0) - ) { - renote = await Notes.findOneBy({ - id: note.renoteId, - }); - } - - const content = renderActivity( - renote - ? renderUndo( - renderAnnounce( - renote.uri || `${config.url}/notes/${renote.id}`, - note, - ), - user, - ) - : renderDelete( - renderTombstone(`${config.url}/notes/${note.id}`), - user, - ), - ); - - deliverToConcerned(user, note, content); - } - - // also deliever delete activity to cascaded notes - const cascadingNotes = (await findCascadingNotes(note)).filter( - (note) => !note.localOnly, - ); // filter out local-only notes - for (const cascadingNote of cascadingNotes) { - if (!cascadingNote.user) continue; - if (!Users.isLocalUser(cascadingNote.user)) continue; - const content = renderActivity( - renderDelete( - renderTombstone(`${config.url}/notes/${cascadingNote.id}`), - cascadingNote.user, - ), - ); - deliverToConcerned(cascadingNote.user, cascadingNote, content); - } - //#endregion - - // 統計を更新 - notesChart.update(note, false); - perUserNotesChart.update(user, note, false); - - if (Users.isRemoteUser(user)) { - registerOrFetchInstanceDoc(user.host).then((i) => { - Instances.decrement({ id: i.id }, "notesCount", 1); - instanceChart.updateNote(i.host, note, false); - }); - } - } - - await Notes.delete({ - id: note.id, - userId: user.id, - }); -} - -async function findCascadingNotes(note: Note) { - const cascadingNotes: Note[] = []; - - const recursive = async (noteId: string) => { - const query = Notes.createQueryBuilder("note") - .where("note.replyId = :noteId", { noteId }) - .orWhere( - new Brackets((q) => { - q.where("note.renoteId = :noteId", { noteId }).andWhere( - "note.text IS NOT NULL", - ); - }), - ) - .leftJoinAndSelect("note.user", "user"); - const replies = await query.getMany(); - for (const reply of replies) { - cascadingNotes.push(reply); - await recursive(reply.id); - } - }; - await recursive(note.id); - - return cascadingNotes.filter((note) => note.userHost === null); // filter out non-local users -} - -async function getMentionedRemoteUsers(note: Note) { - const where = [] as any[]; - - // mention / reply / dm - const uris = ( - JSON.parse(note.mentionedRemoteUsers) as IMentionedRemoteUsers - ).map((x) => x.uri); - if (uris.length > 0) { - where.push({ uri: In(uris) }); - } - - // renote / quote - if (note.renoteUserId) { - where.push({ - id: note.renoteUserId, - }); - } - - if (where.length === 0) return []; - - return (await Users.find({ - where, - })) as IRemoteUser[]; -} - -async function deliverToConcerned( - user: { id: ILocalUser["id"]; host: null }, - note: Note, - content: any, -) { - deliverToFollowers(user, content); - deliverToRelays(user, content); - const remoteUsers = await getMentionedRemoteUsers(note); - for (const remoteUser of remoteUsers) { - deliverToUser(user, content, remoteUser); - } -} diff --git a/packages/backend/src/services/note/polls/update.ts b/packages/backend/src/services/note/polls/update.ts deleted file mode 100644 index e02d48d055..0000000000 --- a/packages/backend/src/services/note/polls/update.ts +++ /dev/null @@ -1,23 +0,0 @@ -import renderUpdate from "@/remote/activitypub/renderer/update.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import renderNote from "@/remote/activitypub/renderer/note.js"; -import { Users, Notes } from "@/models/index.js"; -import type { Note } from "@/models/entities/note.js"; -import { deliverToFollowers } from "@/remote/activitypub/deliver-manager.js"; -import { deliverToRelays } from "../../relay.js"; - -export async function deliverQuestionUpdate(noteId: Note["id"]) { - const note = await Notes.findOneBy({ id: noteId }); - if (note == null) throw new Error("note not found"); - - const user = await Users.findOneBy({ id: note.userId }); - if (user == null) throw new Error("note not found"); - - if (Users.isLocalUser(user)) { - const content = renderActivity( - renderUpdate(await renderNote(note, false), user), - ); - deliverToFollowers(user, content); - deliverToRelays(user, content); - } -} diff --git a/packages/backend/src/services/note/polls/vote.ts b/packages/backend/src/services/note/polls/vote.ts deleted file mode 100644 index 582af0b17b..0000000000 --- a/packages/backend/src/services/note/polls/vote.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { publishNoteStream } from "@/services/stream.js"; -import type { CacheableUser } from "@/models/entities/user.js"; -import { User } from "@/models/entities/user.js"; -import type { Note } from "@/models/entities/note.js"; -import { PollVotes, NoteWatchings, Polls, Blockings } from "@/models/index.js"; -import { Not } from "typeorm"; -import { genId } from "@/misc/gen-id.js"; -import { createNotification } from "../../create-notification.js"; - -export default async function ( - user: CacheableUser, - note: Note, - choice: number, -) { - const poll = await Polls.findOneBy({ noteId: note.id }); - - if (poll == null) throw new Error("poll not found"); - - // Check whether is valid choice - if (poll.choices[choice] == null) throw new Error("invalid choice param"); - - // Check blocking - if (note.userId !== user.id) { - const block = await Blockings.findOneBy({ - blockerId: note.userId, - blockeeId: user.id, - }); - if (block) { - throw new Error("blocked"); - } - } - - // if already voted - const exist = await PollVotes.findBy({ - noteId: note.id, - userId: user.id, - }); - - if (poll.multiple) { - if (exist.some((x) => x.choice === choice)) { - throw new Error("already voted"); - } - } else if (exist.length !== 0) { - throw new Error("already voted"); - } - - // Create vote - await PollVotes.insert({ - id: genId(), - createdAt: new Date(), - noteId: note.id, - userId: user.id, - choice: choice, - }); - - // Increment votes count - const index = choice + 1; // In SQL, array index is 1 based - await Polls.query( - `UPDATE poll SET votes[${index}] = votes[${index}] + 1 WHERE "noteId" = '${poll.noteId}'`, - ); - - publishNoteStream(note.id, "pollVoted", { - choice: choice, - userId: user.id, - }); - - // Notify - createNotification(note.userId, "pollVote", { - notifierId: user.id, - noteId: note.id, - choice: choice, - }); - - // Fetch watchers - NoteWatchings.findBy({ - noteId: note.id, - userId: Not(user.id), - }).then((watchers) => { - for (const watcher of watchers) { - createNotification(watcher.userId, "pollVote", { - notifierId: user.id, - noteId: note.id, - choice: choice, - }); - } - }); -} diff --git a/packages/backend/src/services/note/reaction/create.ts b/packages/backend/src/services/note/reaction/create.ts deleted file mode 100644 index 1a3c52eb51..0000000000 --- a/packages/backend/src/services/note/reaction/create.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { publishNoteStream } from "@/services/stream.js"; -import { renderLike } from "@/remote/activitypub/renderer/like.js"; -import DeliverManager from "@/remote/activitypub/deliver-manager.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import { toDbReaction, decodeReaction } from "@/misc/reaction-lib.js"; -import type { User, IRemoteUser } from "@/models/entities/user.js"; -import type { Note } from "@/models/entities/note.js"; -import { - NoteReactions, - Users, - NoteWatchings, - Notes, - Emojis, - Blockings, -} from "@/models/index.js"; -import { IsNull, Not } from "typeorm"; -import { perUserReactionsChart } from "@/services/chart/index.js"; -import { genId } from "@/misc/gen-id.js"; -import { createNotification } from "../../create-notification.js"; -import deleteReaction from "./delete.js"; -import { isDuplicateKeyValueError } from "@/misc/is-duplicate-key-value-error.js"; -import type { NoteReaction } from "@/models/entities/note-reaction.js"; -import { IdentifiableError } from "@/misc/identifiable-error.js"; - -export default async ( - user: { id: User["id"]; host: User["host"] }, - note: Note, - reaction?: string, -) => { - // Check blocking - if (note.userId !== user.id) { - const block = await Blockings.findOneBy({ - blockerId: note.userId, - blockeeId: user.id, - }); - if (block) { - throw new IdentifiableError("e70412a4-7197-4726-8e74-f3e0deb92aa7"); - } - } - - // check visibility - if (!(await Notes.isVisibleForMe(note, user.id))) { - throw new IdentifiableError( - "68e9d2d1-48bf-42c2-b90a-b20e09fd3d48", - "Note not accessible for you.", - ); - } - - // TODO: cache - reaction = await toDbReaction(reaction, user.host); - - const record: NoteReaction = { - id: genId(), - createdAt: new Date(), - noteId: note.id, - userId: user.id, - reaction, - }; - - // Create reaction - try { - await NoteReactions.insert(record); - } catch (e) { - if (isDuplicateKeyValueError(e)) { - const exists = await NoteReactions.findOneByOrFail({ - noteId: note.id, - userId: user.id, - }); - - if (exists.reaction !== reaction) { - // 別のリアクションがすでにされていたら置き換える - await deleteReaction(user, note); - await NoteReactions.insert(record); - } else { - // 同じリアクションがすでにされていたらエラー - throw new IdentifiableError("51c42bb4-931a-456b-bff7-e5a8a70dd298"); - } - } else { - throw e; - } - } - - // Increment reactions count - const sql = `jsonb_set("reactions", '{${reaction}}', (COALESCE("reactions"->>'${reaction}', '0')::int + 1)::text::jsonb)`; - await Notes.createQueryBuilder() - .update() - .set({ - reactions: () => sql, - score: () => '"score" + 1', - }) - .where("id = :id", { id: note.id }) - .execute(); - - perUserReactionsChart.update(user, note); - - // カスタム絵文字リアクションだったら絵文字情報も送る - const decodedReaction = decodeReaction(reaction); - - const emoji = await Emojis.findOne({ - where: { - name: decodedReaction.name, - host: decodedReaction.host ?? IsNull(), - }, - select: ["name", "host", "originalUrl", "publicUrl"], - }); - - publishNoteStream(note.id, "reacted", { - reaction: decodedReaction.reaction, - emoji: - emoji != null - ? { - name: emoji.host - ? `${emoji.name}@${emoji.host}` - : `${emoji.name}@.`, - url: emoji.publicUrl || emoji.originalUrl, // || emoji.originalUrl してるのは後方互換性のため - } - : null, - userId: user.id, - }); - - // リアクションされたユーザーがローカルユーザーなら通知を作成 - if (note.userHost === null) { - createNotification(note.userId, "reaction", { - notifierId: user.id, - note: note, - noteId: note.id, - reaction: reaction, - }); - } - - // Fetch watchers - NoteWatchings.findBy({ - noteId: note.id, - userId: Not(user.id), - }).then((watchers) => { - for (const watcher of watchers) { - createNotification(watcher.userId, "reaction", { - notifierId: user.id, - note: note, - noteId: note.id, - reaction: reaction, - }); - } - }); - - //#region 配信 - if (Users.isLocalUser(user) && !note.localOnly) { - const content = renderActivity(await renderLike(record, note)); - const dm = new DeliverManager(user, content); - if (note.userHost !== null) { - const reactee = await Users.findOneBy({ id: note.userId }); - dm.addDirectRecipe(reactee as IRemoteUser); - } - - if (["public", "home", "followers"].includes(note.visibility)) { - dm.addFollowersRecipe(); - } else if (note.visibility === "specified") { - const visibleUsers = await Promise.all( - note.visibleUserIds.map((id) => Users.findOneBy({ id })), - ); - for (const u of visibleUsers.filter((u) => u && Users.isRemoteUser(u))) { - dm.addDirectRecipe(u as IRemoteUser); - } - } - - dm.execute(); - } - //#endregion -}; diff --git a/packages/backend/src/services/note/reaction/delete.ts b/packages/backend/src/services/note/reaction/delete.ts deleted file mode 100644 index 82648249e6..0000000000 --- a/packages/backend/src/services/note/reaction/delete.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { publishNoteStream } from "@/services/stream.js"; -import { renderLike } from "@/remote/activitypub/renderer/like.js"; -import renderUndo from "@/remote/activitypub/renderer/undo.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import DeliverManager from "@/remote/activitypub/deliver-manager.js"; -import { IdentifiableError } from "@/misc/identifiable-error.js"; -import type { User, IRemoteUser } from "@/models/entities/user.js"; -import type { Note } from "@/models/entities/note.js"; -import { NoteReactions, Users, Notes } from "@/models/index.js"; -import { decodeReaction } from "@/misc/reaction-lib.js"; - -export default async ( - user: { id: User["id"]; host: User["host"] }, - note: Note, -) => { - // if already unreacted - const exist = await NoteReactions.findOneBy({ - noteId: note.id, - userId: user.id, - }); - - if (exist == null) { - throw new IdentifiableError( - "60527ec9-b4cb-4a88-a6bd-32d3ad26817d", - "not reacted", - ); - } - - // Delete reaction - const result = await NoteReactions.delete(exist.id); - - if (result.affected !== 1) { - throw new IdentifiableError( - "60527ec9-b4cb-4a88-a6bd-32d3ad26817d", - "not reacted", - ); - } - - // Decrement reactions count - const sql = `jsonb_set("reactions", '{${exist.reaction}}', (COALESCE("reactions"->>'${exist.reaction}', '0')::int - 1)::text::jsonb)`; - await Notes.createQueryBuilder() - .update() - .set({ - reactions: () => sql, - }) - .where("id = :id", { id: note.id }) - .execute(); - - Notes.decrement({ id: note.id }, "score", 1); - - publishNoteStream(note.id, "unreacted", { - reaction: decodeReaction(exist.reaction).reaction, - userId: user.id, - }); - - //#region 配信 - if (Users.isLocalUser(user) && !note.localOnly) { - const content = renderActivity( - renderUndo(await renderLike(exist, note), user), - ); - const dm = new DeliverManager(user, content); - if (note.userHost !== null) { - const reactee = await Users.findOneBy({ id: note.userId }); - dm.addDirectRecipe(reactee as IRemoteUser); - } - dm.addFollowersRecipe(); - dm.execute(); - } - //#endregion -}; diff --git a/packages/backend/src/services/note/read.ts b/packages/backend/src/services/note/read.ts deleted file mode 100644 index 53188f15f7..0000000000 --- a/packages/backend/src/services/note/read.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { publishMainStream } from "@/services/stream.js"; -import type { Note } from "@/models/entities/note.js"; -import type { User } from "@/models/entities/user.js"; -import { - NoteUnreads, - AntennaNotes, - Users, - Followings, - ChannelFollowings, -} from "@/models/index.js"; -import { Not, IsNull, In } from "typeorm"; -import type { Channel } from "@/models/entities/channel.js"; -import { checkHitAntenna } from "@/misc/check-hit-antenna.js"; -import { getAntennas } from "@/misc/antenna-cache.js"; -import { readNotificationByQuery } from "@/server/api/common/read-notification.js"; -import type { Packed } from "@/misc/schema.js"; - -/** - * Mark notes as read - */ -export default async function ( - userId: User["id"], - notes: (Note | Packed<"Note">)[], - info?: { - following: Set<User["id"]>; - followingChannels: Set<Channel["id"]>; - }, -) { - const following = info?.following - ? info.following - : new Set<string>( - ( - await Followings.find({ - where: { - followerId: userId, - }, - select: ["followeeId"], - }) - ).map((x) => x.followeeId), - ); - const followingChannels = info?.followingChannels - ? info.followingChannels - : new Set<string>( - ( - await ChannelFollowings.find({ - where: { - followerId: userId, - }, - select: ["followeeId"], - }) - ).map((x) => x.followeeId), - ); - - const myAntennas = (await getAntennas()).filter((a) => a.userId === userId); - const readMentions: (Note | Packed<"Note">)[] = []; - const readSpecifiedNotes: (Note | Packed<"Note">)[] = []; - const readChannelNotes: (Note | Packed<"Note">)[] = []; - const readAntennaNotes: (Note | Packed<"Note">)[] = []; - - for (const note of notes) { - if (note.mentions?.includes(userId)) { - readMentions.push(note); - } else if (note.visibleUserIds?.includes(userId)) { - readSpecifiedNotes.push(note); - } - - if (note.channelId && followingChannels.has(note.channelId)) { - readChannelNotes.push(note); - } - - if (note.user != null) { - // たぶんnullになることは無いはずだけど一応 - for (const antenna of myAntennas) { - if ( - await checkHitAntenna( - antenna, - note, - note.user, - undefined, - Array.from(following), - ) - ) { - readAntennaNotes.push(note); - } - } - } - } - - if ( - readMentions.length > 0 || - readSpecifiedNotes.length > 0 || - readChannelNotes.length > 0 - ) { - // Remove the record - await NoteUnreads.delete({ - userId: userId, - noteId: In([ - ...readMentions.map((n) => n.id), - ...readSpecifiedNotes.map((n) => n.id), - ...readChannelNotes.map((n) => n.id), - ]), - }); - - // TODO: ↓まとめてクエリしたい - - NoteUnreads.countBy({ - userId: userId, - isMentioned: true, - }).then((mentionsCount) => { - if (mentionsCount === 0) { - // 全て既読になったイベントを発行 - publishMainStream(userId, "readAllUnreadMentions"); - } - }); - - NoteUnreads.countBy({ - userId: userId, - isSpecified: true, - }).then((specifiedCount) => { - if (specifiedCount === 0) { - // 全て既読になったイベントを発行 - publishMainStream(userId, "readAllUnreadSpecifiedNotes"); - } - }); - - NoteUnreads.countBy({ - userId: userId, - noteChannelId: Not(IsNull()), - }).then((channelNoteCount) => { - if (channelNoteCount === 0) { - // 全て既読になったイベントを発行 - publishMainStream(userId, "readAllChannels"); - } - }); - - readNotificationByQuery(userId, { - noteId: In([ - ...readMentions.map((n) => n.id), - ...readSpecifiedNotes.map((n) => n.id), - ]), - }); - } - - if (readAntennaNotes.length > 0) { - await AntennaNotes.update( - { - antennaId: In(myAntennas.map((a) => a.id)), - noteId: In(readAntennaNotes.map((n) => n.id)), - }, - { - read: true, - }, - ); - - // TODO: まとめてクエリしたい - for (const antenna of myAntennas) { - const count = await AntennaNotes.countBy({ - antennaId: antenna.id, - read: false, - }); - - if (count === 0) { - publishMainStream(userId, "readAntenna", antenna); - } - } - - Users.getHasUnreadAntenna(userId).then((unread) => { - if (!unread) { - publishMainStream(userId, "readAllAntennas"); - } - }); - } -} diff --git a/packages/backend/src/services/note/unread.ts b/packages/backend/src/services/note/unread.ts deleted file mode 100644 index 275b230d47..0000000000 --- a/packages/backend/src/services/note/unread.ts +++ /dev/null @@ -1,59 +0,0 @@ -import type { Note } from "@/models/entities/note.js"; -import { publishMainStream } from "@/services/stream.js"; -import type { User } from "@/models/entities/user.js"; -import { Mutings, NoteThreadMutings, NoteUnreads } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; - -export async function insertNoteUnread( - userId: User["id"], - note: Note, - params: { - // NOTE: isSpecifiedがtrueならisMentionedは必ずfalse - isSpecified: boolean; - isMentioned: boolean; - }, -) { - //#region ミュートしているなら無視 - // TODO: 現在の仕様ではChannelにミュートは適用されないのでよしなにケアする - const mute = await Mutings.findBy({ - muterId: userId, - }); - if (mute.map((m) => m.muteeId).includes(note.userId)) return; - //#endregion - - // スレッドミュート - const threadMute = await NoteThreadMutings.findOneBy({ - userId: userId, - threadId: note.threadId || note.id, - }); - if (threadMute) return; - - const unread = { - id: genId(), - noteId: note.id, - userId: userId, - isSpecified: params.isSpecified, - isMentioned: params.isMentioned, - noteChannelId: note.channelId, - noteUserId: note.userId, - }; - - await NoteUnreads.insert(unread); - - // 2秒経っても既読にならなかったら「未読の投稿がありますよ」イベントを発行する - setTimeout(async () => { - const exist = await NoteUnreads.findOneBy({ id: unread.id }); - - if (exist == null) return; - - if (params.isMentioned) { - publishMainStream(userId, "unreadMention", note.id); - } - if (params.isSpecified) { - publishMainStream(userId, "unreadSpecifiedNote", note.id); - } - if (note.channelId) { - publishMainStream(userId, "unreadChannel", note.id); - } - }, 2000); -} diff --git a/packages/backend/src/services/note/unwatch.ts b/packages/backend/src/services/note/unwatch.ts deleted file mode 100644 index b4da5e86da..0000000000 --- a/packages/backend/src/services/note/unwatch.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { User } from "@/models/entities/user.js"; -import { NoteWatchings } from "@/models/index.js"; -import type { Note } from "@/models/entities/note.js"; - -export default async (me: User["id"], note: Note) => { - await NoteWatchings.delete({ - noteId: note.id, - userId: me, - }); -}; diff --git a/packages/backend/src/services/note/watch.ts b/packages/backend/src/services/note/watch.ts deleted file mode 100644 index 2a99dd6949..0000000000 --- a/packages/backend/src/services/note/watch.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { User } from "@/models/entities/user.js"; -import type { Note } from "@/models/entities/note.js"; -import { NoteWatchings } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import type { NoteWatching } from "@/models/entities/note-watching.js"; - -export default async (me: User["id"], note: Note) => { - // 自分の投稿はwatchできない - if (me === note.userId) { - return; - } - - await NoteWatchings.insert({ - id: genId(), - createdAt: new Date(), - noteId: note.id, - userId: me, - noteUserId: note.userId, - } as NoteWatching); -}; diff --git a/packages/backend/src/services/push-notification.ts b/packages/backend/src/services/push-notification.ts deleted file mode 100644 index a207fae391..0000000000 --- a/packages/backend/src/services/push-notification.ts +++ /dev/null @@ -1,116 +0,0 @@ -import push from "web-push"; -import config from "@/config/index.js"; -import { SwSubscriptions } from "@/models/index.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import type { Packed } from "@/misc/schema.js"; -import { getNoteSummary } from "@/misc/get-note-summary.js"; - -// Defined also packages/sw/types.ts#L14-L21 -type pushNotificationsTypes = { - notification: Packed<"Notification">; - unreadMessagingMessage: Packed<"MessagingMessage">; - readNotifications: { notificationIds: string[] }; - readAllNotifications: undefined; - readAllMessagingMessages: undefined; - readAllMessagingMessagesOfARoom: { userId: string } | { groupId: string }; -}; - -// プッシュメッセージサーバーには文字数制限があるため、内容を削減します -function truncateNotification(notification: Packed<"Notification">): any { - if (notification.note) { - return { - ...notification, - note: { - ...notification.note, - // textをgetNoteSummaryしたものに置き換える - text: getNoteSummary( - notification.type === "renote" - ? (notification.note.renote as Packed<"Note">) - : notification.note, - ), - - cw: undefined, - reply: undefined, - renote: undefined, - user: undefined as any, // 通知を受け取ったユーザーである場合が多いのでこれも捨てる - }, - }; - } - - return notification; -} - -export async function pushNotification<T extends keyof pushNotificationsTypes>( - userId: string, - type: T, - body: pushNotificationsTypes[T], -) { - const meta = await fetchMeta(); - - if ( - !meta.enableServiceWorker || - meta.swPublicKey == null || - meta.swPrivateKey == null - ) - return; - - // アプリケーションの連絡先と、サーバーサイドの鍵ペアの情報を登録 - push.setVapidDetails(config.url, meta.swPublicKey, meta.swPrivateKey); - - // Fetch - const subscriptions = await SwSubscriptions.findBy({ - userId: userId, - }); - - for (const subscription of subscriptions) { - if ( - [ - "readNotifications", - "readAllNotifications", - "readAllMessagingMessages", - "readAllMessagingMessagesOfARoom", - ].includes(type) && - !subscription.sendReadMessage - ) - continue; - - const pushSubscription = { - endpoint: subscription.endpoint, - keys: { - auth: subscription.auth, - p256dh: subscription.publickey, - }, - }; - - push - .sendNotification( - pushSubscription, - JSON.stringify({ - type, - body: - type === "notification" - ? truncateNotification(body as Packed<"Notification">) - : body, - userId, - dateTime: new Date().getTime(), - }), - { - proxy: config.proxy, - }, - ) - .catch((err: any) => { - //swLogger.info(err.statusCode); - //swLogger.info(err.headers); - //swLogger.info(err.body); - - if (err.statusCode === 410) { - SwSubscriptions.delete({ - userId: userId, - endpoint: subscription.endpoint, - auth: subscription.auth, - publickey: subscription.publickey, - }); - } - }); - } -} diff --git a/packages/backend/src/services/register-or-fetch-instance-doc.ts b/packages/backend/src/services/register-or-fetch-instance-doc.ts deleted file mode 100644 index 4c3570e907..0000000000 --- a/packages/backend/src/services/register-or-fetch-instance-doc.ts +++ /dev/null @@ -1,33 +0,0 @@ -import type { Instance } from "@/models/entities/instance.js"; -import { Instances } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import { toPuny } from "@/misc/convert-host.js"; -import { Cache } from "@/misc/cache.js"; - -const cache = new Cache<Instance>(1000 * 60 * 60); - -export async function registerOrFetchInstanceDoc( - host: string, -): Promise<Instance> { - host = toPuny(host); - - const cached = cache.get(host); - if (cached) return cached; - - const index = await Instances.findOneBy({ host }); - - if (index == null) { - const i = await Instances.insert({ - id: genId(), - host, - caughtAt: new Date(), - lastCommunicatedAt: new Date(), - }).then((x) => Instances.findOneByOrFail(x.identifiers[0])); - - cache.set(host, i); - return i; - } else { - cache.set(host, index); - return index; - } -} diff --git a/packages/backend/src/services/relay.ts b/packages/backend/src/services/relay.ts deleted file mode 100644 index 244e05c030..0000000000 --- a/packages/backend/src/services/relay.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { IsNull } from "typeorm"; -import { renderFollowRelay } from "@/remote/activitypub/renderer/follow-relay.js"; -import { - renderActivity, - attachLdSignature, -} from "@/remote/activitypub/renderer/index.js"; -import renderUndo from "@/remote/activitypub/renderer/undo.js"; -import { deliver } from "@/queue/index.js"; -import type { ILocalUser, User } from "@/models/entities/user.js"; -import { Users, Relays } from "@/models/index.js"; -import { genId } from "@/misc/gen-id.js"; -import { Cache } from "@/misc/cache.js"; -import type { Relay } from "@/models/entities/relay.js"; -import { createSystemUser } from "./create-system-user.js"; - -const ACTOR_USERNAME = "relay.actor" as const; - -const relaysCache = new Cache<Relay[]>(1000 * 60 * 10); - -export async function getRelayActor(): Promise<ILocalUser> { - const user = await Users.findOneBy({ - host: IsNull(), - username: ACTOR_USERNAME, - }); - - if (user) return user as ILocalUser; - - const created = await createSystemUser(ACTOR_USERNAME); - return created as ILocalUser; -} - -export async function addRelay(inbox: string) { - const relay = await Relays.insert({ - id: genId(), - inbox, - status: "requesting", - }).then((x) => Relays.findOneByOrFail(x.identifiers[0])); - - const relayActor = await getRelayActor(); - const follow = await renderFollowRelay(relay, relayActor); - const activity = renderActivity(follow); - deliver(relayActor, activity, relay.inbox); - - return relay; -} - -export async function removeRelay(inbox: string) { - const relay = await Relays.findOneBy({ - inbox, - }); - - if (relay == null) { - throw new Error("relay not found"); - } - - const relayActor = await getRelayActor(); - const follow = renderFollowRelay(relay, relayActor); - const undo = renderUndo(follow, relayActor); - const activity = renderActivity(undo); - deliver(relayActor, activity, relay.inbox); - - await Relays.delete(relay.id); -} - -export async function listRelay() { - const relays = await Relays.find(); - return relays; -} - -export async function relayAccepted(id: string) { - const result = await Relays.update(id, { - status: "accepted", - }); - - return JSON.stringify(result); -} - -export async function relayRejected(id: string) { - const result = await Relays.update(id, { - status: "rejected", - }); - - return JSON.stringify(result); -} - -export async function deliverToRelays( - user: { id: User["id"]; host: null }, - activity: any, -) { - if (activity == null) return; - - const relays = await relaysCache.fetch(null, () => - Relays.findBy({ - status: "accepted", - }), - ); - if (relays.length === 0) return; - - // TODO - //const copy = structuredClone(activity); - const copy = JSON.parse(JSON.stringify(activity)); - if (!copy.to) copy.to = ["https://www.w3.org/ns/activitystreams#Public"]; - - const signed = await attachLdSignature(copy, user); - - for (const relay of relays) { - deliver(user, signed, relay.inbox); - } -} diff --git a/packages/backend/src/services/send-email-notification.ts b/packages/backend/src/services/send-email-notification.ts deleted file mode 100644 index 14a9754fe5..0000000000 --- a/packages/backend/src/services/send-email-notification.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { UserProfiles } from "@/models/index.js"; -import type { User } from "@/models/entities/user.js"; -import { sendEmail } from "./send-email.js"; -import { I18n } from "@/misc/i18n.js"; -import * as Acct from "@/misc/acct.js"; -// TODO -//const locales = await import('../../../../locales/index.js'); - -// TODO: locale ファイルをクライアント用とサーバー用で分けたい - -async function follow(userId: User["id"], follower: User) { - /* - const userProfile = await UserProfiles.findOneByOrFail({ userId: userId }); - if (!userProfile.email || !userProfile.emailNotificationTypes.includes('follow')) return; - const locale = locales[userProfile.lang || 'ja-JP']; - const i18n = new I18n(locale); - // TODO: render user information html - sendEmail(userProfile.email, i18n.t('_email._follow.title'), `${follower.name} (@${Acct.toString(follower)})`, `${follower.name} (@${Acct.toString(follower)})`); - */ -} - -async function receiveFollowRequest(userId: User["id"], follower: User) { - /* - const userProfile = await UserProfiles.findOneByOrFail({ userId: userId }); - if (!userProfile.email || !userProfile.emailNotificationTypes.includes('receiveFollowRequest')) return; - const locale = locales[userProfile.lang || 'ja-JP']; - const i18n = new I18n(locale); - // TODO: render user information html - sendEmail(userProfile.email, i18n.t('_email._receiveFollowRequest.title'), `${follower.name} (@${Acct.toString(follower)})`, `${follower.name} (@${Acct.toString(follower)})`); - */ -} - -export const sendEmailNotification = { - follow, - receiveFollowRequest, -}; diff --git a/packages/backend/src/services/send-email.ts b/packages/backend/src/services/send-email.ts deleted file mode 100644 index 4c442a168c..0000000000 --- a/packages/backend/src/services/send-email.ts +++ /dev/null @@ -1,132 +0,0 @@ -import * as nodemailer from "nodemailer"; -import { fetchMeta } from "@/misc/fetch-meta.js"; -import Logger from "./logger.js"; -import config from "@/config/index.js"; - -export const logger = new Logger("email"); - -export async function sendEmail( - to: string, - subject: string, - html: string, - text: string, -) { - const meta = await fetchMeta(true); - - const iconUrl = `${config.url}/static-assets/mi-white.png`; - const emailSettingUrl = `${config.url}/settings/email`; - - const enableAuth = meta.smtpUser != null && meta.smtpUser !== ""; - - const transporter = nodemailer.createTransport({ - host: meta.smtpHost, - port: meta.smtpPort, - secure: meta.smtpSecure, - ignoreTLS: !enableAuth, - proxy: config.proxySmtp, - auth: enableAuth - ? { - user: meta.smtpUser, - pass: meta.smtpPass, - } - : undefined, - } as any); - - try { - // TODO: htmlサニタイズ - const info = await transporter.sendMail({ - from: meta.email!, - to: to, - subject: subject, - text: text, - html: `<!DOCTYPE html> -<html> - <head> - <meta charset="utf-8"> - <title>${subject}</title> - <style> - html { - background: #191724; - } - - body { - padding: 16px; - margin: 0; - font-family: sans-serif; - font-size: 14px; - } - - a { - text-decoration: none; - color: #31748f; - } - a:hover { - text-decoration: underline; - } - - main { - max-width: 500px; - margin: 0 auto; - background: #1f1d2e; - color: #e0def4; - } - main > header { - padding: 32px; - background: #31748f; - display: flex; - } - main > header > img { - max-width: 128px; - max-height: 72px; - vertical-align: bottom; - margin-right: 16px; - } - main > article { - padding: 32px; - } - main > article > h1 { - margin: 0 0 1em 0; - } - main > footer { - padding: 32px; - border-top: solid 1px #26233a; - } - - nav { - box-sizing: border-box; - max-width: 500px; - margin: 16px auto 0 auto; - padding: 0 32px; - } - nav > a { - color: #6e6a86; - } - </style> - </head> - <body> - <main> - <header> - <img src="${meta.logoImageUrl || meta.iconUrl || iconUrl}" height="100"/> - <h1>${meta.name}</h1> - </header> - <article> - <h1>${subject}</h1> - <div>${html}</div> - </article> - <footer> - <a href="${emailSettingUrl}">${"Email setting"}</a> - </footer> - </main> - <nav> - <a href="${config.url}">${config.host}</a> - </nav> - </body> -</html>`, - }); - - logger.info(`Message sent: ${info.messageId}`); - } catch (err) { - logger.error(err as Error); - throw err; - } -} diff --git a/packages/backend/src/services/stream.ts b/packages/backend/src/services/stream.ts deleted file mode 100644 index f3846feaf1..0000000000 --- a/packages/backend/src/services/stream.ts +++ /dev/null @@ -1,226 +0,0 @@ -import { redisClient } from "../db/redis.js"; -import type { User } from "@/models/entities/user.js"; -import type { Note } from "@/models/entities/note.js"; -import type { UserList } from "@/models/entities/user-list.js"; -import type { UserGroup } from "@/models/entities/user-group.js"; -import config from "@/config/index.js"; -import type { Antenna } from "@/models/entities/antenna.js"; -import type { Channel } from "@/models/entities/channel.js"; -import type { - StreamChannels, - AdminStreamTypes, - AntennaStreamTypes, - BroadcastTypes, - ChannelStreamTypes, - DriveStreamTypes, - GroupMessagingStreamTypes, - InternalStreamTypes, - MainStreamTypes, - MessagingIndexStreamTypes, - MessagingStreamTypes, - NoteStreamTypes, - UserListStreamTypes, - UserStreamTypes, -} from "@/server/api/stream/types.js"; - -class Publisher { - private publish = ( - channel: StreamChannels, - type: string | null, - value?: any, - ): void => { - const message = - type == null - ? value - : value == null - ? { type: type, body: null } - : { type: type, body: value }; - - redisClient.publish( - config.host, - JSON.stringify({ - channel: channel, - message: message, - }), - ); - }; - - public publishInternalEvent = <K extends keyof InternalStreamTypes>( - type: K, - value?: InternalStreamTypes[K], - ): void => { - this.publish("internal", type, typeof value === "undefined" ? null : value); - }; - - public publishUserEvent = <K extends keyof UserStreamTypes>( - userId: User["id"], - type: K, - value?: UserStreamTypes[K], - ): void => { - this.publish( - `user:${userId}`, - type, - typeof value === "undefined" ? null : value, - ); - }; - - public publishBroadcastStream = <K extends keyof BroadcastTypes>( - type: K, - value?: BroadcastTypes[K], - ): void => { - this.publish( - "broadcast", - type, - typeof value === "undefined" ? null : value, - ); - }; - - public publishMainStream = <K extends keyof MainStreamTypes>( - userId: User["id"], - type: K, - value?: MainStreamTypes[K], - ): void => { - this.publish( - `mainStream:${userId}`, - type, - typeof value === "undefined" ? null : value, - ); - }; - - public publishDriveStream = <K extends keyof DriveStreamTypes>( - userId: User["id"], - type: K, - value?: DriveStreamTypes[K], - ): void => { - this.publish( - `driveStream:${userId}`, - type, - typeof value === "undefined" ? null : value, - ); - }; - - public publishNoteStream = <K extends keyof NoteStreamTypes>( - noteId: Note["id"], - type: K, - value?: NoteStreamTypes[K], - ): void => { - this.publish(`noteStream:${noteId}`, type, { - id: noteId, - body: value, - }); - }; - - public publishChannelStream = <K extends keyof ChannelStreamTypes>( - channelId: Channel["id"], - type: K, - value?: ChannelStreamTypes[K], - ): void => { - this.publish( - `channelStream:${channelId}`, - type, - typeof value === "undefined" ? null : value, - ); - }; - - public publishUserListStream = <K extends keyof UserListStreamTypes>( - listId: UserList["id"], - type: K, - value?: UserListStreamTypes[K], - ): void => { - this.publish( - `userListStream:${listId}`, - type, - typeof value === "undefined" ? null : value, - ); - }; - - public publishAntennaStream = <K extends keyof AntennaStreamTypes>( - antennaId: Antenna["id"], - type: K, - value?: AntennaStreamTypes[K], - ): void => { - this.publish( - `antennaStream:${antennaId}`, - type, - typeof value === "undefined" ? null : value, - ); - }; - - public publishMessagingStream = <K extends keyof MessagingStreamTypes>( - userId: User["id"], - otherpartyId: User["id"], - type: K, - value?: MessagingStreamTypes[K], - ): void => { - this.publish( - `messagingStream:${userId}-${otherpartyId}`, - type, - typeof value === "undefined" ? null : value, - ); - }; - - public publishGroupMessagingStream = < - K extends keyof GroupMessagingStreamTypes, - >( - groupId: UserGroup["id"], - type: K, - value?: GroupMessagingStreamTypes[K], - ): void => { - this.publish( - `messagingStream:${groupId}`, - type, - typeof value === "undefined" ? null : value, - ); - }; - - public publishMessagingIndexStream = < - K extends keyof MessagingIndexStreamTypes, - >( - userId: User["id"], - type: K, - value?: MessagingIndexStreamTypes[K], - ): void => { - this.publish( - `messagingIndexStream:${userId}`, - type, - typeof value === "undefined" ? null : value, - ); - }; - - public publishNotesStream = (note: Note): void => { - this.publish("notesStream", null, note); - }; - - public publishAdminStream = <K extends keyof AdminStreamTypes>( - userId: User["id"], - type: K, - value?: AdminStreamTypes[K], - ): void => { - this.publish( - `adminStream:${userId}`, - type, - typeof value === "undefined" ? null : value, - ); - }; -} - -const publisher = new Publisher(); - -export default publisher; - -export const publishInternalEvent = publisher.publishInternalEvent; -export const publishUserEvent = publisher.publishUserEvent; -export const publishBroadcastStream = publisher.publishBroadcastStream; -export const publishMainStream = publisher.publishMainStream; -export const publishDriveStream = publisher.publishDriveStream; -export const publishNoteStream = publisher.publishNoteStream; -export const publishNotesStream = publisher.publishNotesStream; -export const publishChannelStream = publisher.publishChannelStream; -export const publishUserListStream = publisher.publishUserListStream; -export const publishAntennaStream = publisher.publishAntennaStream; -export const publishMessagingStream = publisher.publishMessagingStream; -export const publishGroupMessagingStream = - publisher.publishGroupMessagingStream; -export const publishMessagingIndexStream = - publisher.publishMessagingIndexStream; -export const publishAdminStream = publisher.publishAdminStream; diff --git a/packages/backend/src/services/suspend-user.ts b/packages/backend/src/services/suspend-user.ts deleted file mode 100644 index f72b8ffcb1..0000000000 --- a/packages/backend/src/services/suspend-user.ts +++ /dev/null @@ -1,47 +0,0 @@ -import renderDelete from "@/remote/activitypub/renderer/delete.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import { deliver } from "@/queue/index.js"; -import config from "@/config/index.js"; -import type { User } from "@/models/entities/user.js"; -import { Users, Followings } from "@/models/index.js"; -import { Not, IsNull } from "typeorm"; -import { publishInternalEvent } from "@/services/stream.js"; - -export async function doPostSuspend(user: { - id: User["id"]; - host: User["host"]; -}) { - publishInternalEvent("userChangeSuspendedState", { - id: user.id, - isSuspended: true, - }); - - if (Users.isLocalUser(user)) { - // Send Delete to all known SharedInboxes - const content = renderActivity( - renderDelete(`${config.url}/users/${user.id}`, user), - ); - - const queue: string[] = []; - - const followings = await Followings.find({ - where: [ - { followerSharedInbox: Not(IsNull()) }, - { followeeSharedInbox: Not(IsNull()) }, - ], - select: ["followerSharedInbox", "followeeSharedInbox"], - }); - - const inboxes = followings.map( - (x) => x.followerSharedInbox || x.followeeSharedInbox, - ); - - for (const inbox of inboxes) { - if (inbox != null && !queue.includes(inbox)) queue.push(inbox); - } - - for (const inbox of queue) { - deliver(user, content, inbox); - } - } -} diff --git a/packages/backend/src/services/unsuspend-user.ts b/packages/backend/src/services/unsuspend-user.ts deleted file mode 100644 index 69447a4a26..0000000000 --- a/packages/backend/src/services/unsuspend-user.ts +++ /dev/null @@ -1,45 +0,0 @@ -import renderDelete from "@/remote/activitypub/renderer/delete.js"; -import renderUndo from "@/remote/activitypub/renderer/undo.js"; -import { renderActivity } from "@/remote/activitypub/renderer/index.js"; -import { deliver } from "@/queue/index.js"; -import config from "@/config/index.js"; -import type { User } from "@/models/entities/user.js"; -import { Users, Followings } from "@/models/index.js"; -import { Not, IsNull } from "typeorm"; -import { publishInternalEvent } from "@/services/stream.js"; - -export async function doPostUnsuspend(user: User) { - publishInternalEvent("userChangeSuspendedState", { - id: user.id, - isSuspended: false, - }); - - if (Users.isLocalUser(user)) { - // 知り得る全SharedInboxにUndo Delete配信 - const content = renderActivity( - renderUndo(renderDelete(`${config.url}/users/${user.id}`, user), user), - ); - - const queue: string[] = []; - - const followings = await Followings.find({ - where: [ - { followerSharedInbox: Not(IsNull()) }, - { followeeSharedInbox: Not(IsNull()) }, - ], - select: ["followerSharedInbox", "followeeSharedInbox"], - }); - - const inboxes = followings.map( - (x) => x.followerSharedInbox || x.followeeSharedInbox, - ); - - for (const inbox of inboxes) { - if (inbox != null && !queue.includes(inbox)) queue.push(inbox); - } - - for (const inbox of queue) { - deliver(user as any, content, inbox); - } - } -} diff --git a/packages/backend/src/services/update-hashtag.ts b/packages/backend/src/services/update-hashtag.ts deleted file mode 100644 index 0c65b08f0a..0000000000 --- a/packages/backend/src/services/update-hashtag.ts +++ /dev/null @@ -1,158 +0,0 @@ -import type { User } from "@/models/entities/user.js"; -import { Hashtags, Users } from "@/models/index.js"; -import { hashtagChart } from "@/services/chart/index.js"; -import { genId } from "@/misc/gen-id.js"; -import type { Hashtag } from "@/models/entities/hashtag.js"; -import { normalizeForSearch } from "@/misc/normalize-for-search.js"; - -export async function updateHashtags( - user: { id: User["id"]; host: User["host"] }, - tags: string[], -) { - for (const tag of tags) { - await updateHashtag(user, tag); - } -} - -export async function updateUsertags(user: User, tags: string[]) { - for (const tag of tags) { - await updateHashtag(user, tag, true, true); - } - - for (const tag of (user.tags || []).filter((x) => !tags.includes(x))) { - await updateHashtag(user, tag, true, false); - } -} - -export async function updateHashtag( - user: { id: User["id"]; host: User["host"] }, - tag: string, - isUserAttached = false, - inc = true, -) { - tag = normalizeForSearch(tag); - - const index = await Hashtags.findOneBy({ name: tag }); - - if (index == null && !inc) return; - - if (index != null) { - const q = Hashtags.createQueryBuilder("tag") - .update() - .where("name = :name", { name: tag }); - - const set = {} as any; - - if (isUserAttached) { - if (inc) { - // 自分が初めてこのタグを使ったなら - if (!index.attachedUserIds.some((id) => id === user.id)) { - set.attachedUserIds = () => - `array_append("attachedUserIds", '${user.id}')`; - set.attachedUsersCount = () => `"attachedUsersCount" + 1`; - } - // 自分が(ローカル内で)初めてこのタグを使ったなら - if ( - Users.isLocalUser(user) && - !index.attachedLocalUserIds.some((id) => id === user.id) - ) { - set.attachedLocalUserIds = () => - `array_append("attachedLocalUserIds", '${user.id}')`; - set.attachedLocalUsersCount = () => `"attachedLocalUsersCount" + 1`; - } - // 自分が(リモートで)初めてこのタグを使ったなら - if ( - Users.isRemoteUser(user) && - !index.attachedRemoteUserIds.some((id) => id === user.id) - ) { - set.attachedRemoteUserIds = () => - `array_append("attachedRemoteUserIds", '${user.id}')`; - set.attachedRemoteUsersCount = () => `"attachedRemoteUsersCount" + 1`; - } - } else { - set.attachedUserIds = () => - `array_remove("attachedUserIds", '${user.id}')`; - set.attachedUsersCount = () => `"attachedUsersCount" - 1`; - if (Users.isLocalUser(user)) { - set.attachedLocalUserIds = () => - `array_remove("attachedLocalUserIds", '${user.id}')`; - set.attachedLocalUsersCount = () => `"attachedLocalUsersCount" - 1`; - } else { - set.attachedRemoteUserIds = () => - `array_remove("attachedRemoteUserIds", '${user.id}')`; - set.attachedRemoteUsersCount = () => `"attachedRemoteUsersCount" - 1`; - } - } - } else { - // 自分が初めてこのタグを使ったなら - if (!index.mentionedUserIds.some((id) => id === user.id)) { - set.mentionedUserIds = () => - `array_append("mentionedUserIds", '${user.id}')`; - set.mentionedUsersCount = () => `"mentionedUsersCount" + 1`; - } - // 自分が(ローカル内で)初めてこのタグを使ったなら - if ( - Users.isLocalUser(user) && - !index.mentionedLocalUserIds.some((id) => id === user.id) - ) { - set.mentionedLocalUserIds = () => - `array_append("mentionedLocalUserIds", '${user.id}')`; - set.mentionedLocalUsersCount = () => `"mentionedLocalUsersCount" + 1`; - } - // 自分が(リモートで)初めてこのタグを使ったなら - if ( - Users.isRemoteUser(user) && - !index.mentionedRemoteUserIds.some((id) => id === user.id) - ) { - set.mentionedRemoteUserIds = () => - `array_append("mentionedRemoteUserIds", '${user.id}')`; - set.mentionedRemoteUsersCount = () => `"mentionedRemoteUsersCount" + 1`; - } - } - - if (Object.keys(set).length > 0) { - q.set(set); - q.execute(); - } - } else { - if (isUserAttached) { - Hashtags.insert({ - id: genId(), - name: tag, - mentionedUserIds: [], - mentionedUsersCount: 0, - mentionedLocalUserIds: [], - mentionedLocalUsersCount: 0, - mentionedRemoteUserIds: [], - mentionedRemoteUsersCount: 0, - attachedUserIds: [user.id], - attachedUsersCount: 1, - attachedLocalUserIds: Users.isLocalUser(user) ? [user.id] : [], - attachedLocalUsersCount: Users.isLocalUser(user) ? 1 : 0, - attachedRemoteUserIds: Users.isRemoteUser(user) ? [user.id] : [], - attachedRemoteUsersCount: Users.isRemoteUser(user) ? 1 : 0, - } as Hashtag); - } else { - Hashtags.insert({ - id: genId(), - name: tag, - mentionedUserIds: [user.id], - mentionedUsersCount: 1, - mentionedLocalUserIds: Users.isLocalUser(user) ? [user.id] : [], - mentionedLocalUsersCount: Users.isLocalUser(user) ? 1 : 0, - mentionedRemoteUserIds: Users.isRemoteUser(user) ? [user.id] : [], - mentionedRemoteUsersCount: Users.isRemoteUser(user) ? 1 : 0, - attachedUserIds: [], - attachedUsersCount: 0, - attachedLocalUserIds: [], - attachedLocalUsersCount: 0, - attachedRemoteUserIds: [], - attachedRemoteUsersCount: 0, - } as Hashtag); - } - } - - if (!isUserAttached) { - hashtagChart.update(tag, user); - } -} diff --git a/packages/backend/src/services/user-cache.ts b/packages/backend/src/services/user-cache.ts deleted file mode 100644 index 9492448554..0000000000 --- a/packages/backend/src/services/user-cache.ts +++ /dev/null @@ -1,63 +0,0 @@ -import type { - CacheableLocalUser, - CacheableUser, - ILocalUser, -} from "@/models/entities/user.js"; -import { User } from "@/models/entities/user.js"; -import { Users } from "@/models/index.js"; -import { Cache } from "@/misc/cache.js"; -import { subscriber } from "@/db/redis.js"; - -export const userByIdCache = new Cache<CacheableUser>(Infinity); -export const localUserByNativeTokenCache = new Cache<CacheableLocalUser | null>( - Infinity, -); -export const localUserByIdCache = new Cache<CacheableLocalUser>(Infinity); -export const uriPersonCache = new Cache<CacheableUser | null>(Infinity); - -subscriber.on("message", async (_, data) => { - const obj = JSON.parse(data); - - if (obj.channel === "internal") { - const { type, body } = obj.message; - switch (type) { - case "localUserUpdated": { - userByIdCache.delete(body.id); - localUserByIdCache.delete(body.id); - localUserByNativeTokenCache.cache.forEach((v, k) => { - if (v.value?.id === body.id) { - localUserByNativeTokenCache.delete(k); - } - }); - break; - } - case "userChangeSuspendedState": - case "userChangeSilencedState": - case "userChangeModeratorState": - case "remoteUserUpdated": { - const user = await Users.findOneByOrFail({ id: body.id }); - userByIdCache.set(user.id, user); - for (const [k, v] of uriPersonCache.cache.entries()) { - if (v.value?.id === user.id) { - uriPersonCache.set(k, user); - } - } - if (Users.isLocalUser(user)) { - localUserByNativeTokenCache.set(user.token, user); - localUserByIdCache.set(user.id, user); - } - break; - } - case "userTokenRegenerated": { - const user = (await Users.findOneByOrFail({ - id: body.id, - })) as ILocalUser; - localUserByNativeTokenCache.delete(body.oldToken); - localUserByNativeTokenCache.set(body.newToken, user); - break; - } - default: - break; - } - } -}); diff --git a/packages/backend/src/services/user-list/push.ts b/packages/backend/src/services/user-list/push.ts deleted file mode 100644 index 01bb066019..0000000000 --- a/packages/backend/src/services/user-list/push.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { publishUserListStream } from "@/services/stream.js"; -import type { User } from "@/models/entities/user.js"; -import type { UserList } from "@/models/entities/user-list.js"; -import { UserListJoinings, Users } from "@/models/index.js"; -import type { UserListJoining } from "@/models/entities/user-list-joining.js"; -import { genId } from "@/misc/gen-id.js"; -import { fetchProxyAccount } from "@/misc/fetch-proxy-account.js"; -import createFollowing from "../following/create.js"; - -export async function pushUserToUserList(target: User, list: UserList) { - await UserListJoinings.insert({ - id: genId(), - createdAt: new Date(), - userId: target.id, - userListId: list.id, - } as UserListJoining); - - publishUserListStream(list.id, "userAdded", await Users.pack(target)); - - // このインスタンス内にこのリモートユーザーをフォローしているユーザーがいなくても投稿を受け取るためにダミーのユーザーがフォローしたということにする - if (Users.isRemoteUser(target)) { - const proxy = await fetchProxyAccount(); - if (proxy) { - createFollowing(proxy, target); - } - } -} diff --git a/packages/backend/src/services/validate-email-for-account.ts b/packages/backend/src/services/validate-email-for-account.ts deleted file mode 100644 index 2bb5e93e7e..0000000000 --- a/packages/backend/src/services/validate-email-for-account.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { validate as validateEmail } from "deep-email-validator"; -import { UserProfiles } from "@/models/index.js"; -import { fetchMeta } from "@/misc/fetch-meta.js"; - -export async function validateEmailForAccount(emailAddress: string): Promise<{ - available: boolean; - reason: null | "used" | "format" | "disposable" | "mx" | "smtp"; -}> { - const meta = await fetchMeta(); - - const exist = await UserProfiles.countBy({ - emailVerified: true, - email: emailAddress, - }); - - const validated = meta.enableActiveEmailValidation - ? await validateEmail({ - email: emailAddress, - validateRegex: true, - validateMx: true, - validateTypo: false, // TLDを見ているみたいだけどclubとか弾かれるので - validateDisposable: true, // 捨てアドかどうかチェック - validateSMTP: false, // 日本だと25ポートが殆どのプロバイダーで塞がれていてタイムアウトになるので - }) - : { valid: true }; - - const available = exist === 0 && validated.valid; - - return { - available, - reason: available - ? null - : exist !== 0 - ? "used" - : validated.reason === "regex" - ? "format" - : validated.reason === "disposable" - ? "disposable" - : validated.reason === "mx" - ? "mx" - : validated.reason === "smtp" - ? "smtp" - : null, - }; -} diff --git a/packages/backend/src/types.ts b/packages/backend/src/types.ts deleted file mode 100644 index 9e53440a17..0000000000 --- a/packages/backend/src/types.ts +++ /dev/null @@ -1,25 +0,0 @@ -export const notificationTypes = [ - "follow", - "mention", - "reply", - "renote", - "quote", - "reaction", - "pollVote", - "pollEnded", - "receiveFollowRequest", - "followRequestAccepted", - "groupInvited", - "app", -] as const; - -export const noteVisibilities = [ - "public", - "home", - "followers", - "specified", -] as const; - -export const mutedNoteReasons = ["word", "manual", "spam", "other"] as const; - -export const ffVisibility = ["public", "followers", "private"] as const; diff --git a/packages/backend/test/activitypub.ts b/packages/backend/test/activitypub.ts deleted file mode 100644 index 7b6f85f5a1..0000000000 --- a/packages/backend/test/activitypub.ts +++ /dev/null @@ -1,102 +0,0 @@ -process.env.NODE_ENV = "test"; - -import * as assert from "assert"; -import rndstr from "rndstr"; -import { initDb } from "../src/db/postgre.js"; -import { initTestDb } from "./utils.js"; - -describe("ActivityPub", () => { - before(async () => { - //await initTestDb(); - await initDb(); - }); - - describe("Parse minimum object", () => { - const host = "https://host1.test"; - const preferredUsername = `${rndstr("A-Z", 4)}${rndstr("a-z", 4)}`; - const actorId = `${host}/users/${preferredUsername.toLowerCase()}`; - - const actor = { - "@context": "https://www.w3.org/ns/activitystreams", - id: actorId, - type: "Person", - preferredUsername, - inbox: `${actorId}/inbox`, - outbox: `${actorId}/outbox`, - }; - - const post = { - "@context": "https://www.w3.org/ns/activitystreams", - id: `${host}/users/${rndstr("0-9a-z", 8)}`, - type: "Note", - attributedTo: actor.id, - to: "https://www.w3.org/ns/activitystreams#Public", - content: "あ", - }; - - it("Minimum Actor", async () => { - const { MockResolver } = await import("./misc/mock-resolver.js"); - const { createPerson } = await import( - "../src/remote/activitypub/models/person.js" - ); - - const resolver = new MockResolver(); - resolver._register(actor.id, actor); - - const user = await createPerson(actor.id, resolver); - - assert.deepStrictEqual(user.uri, actor.id); - assert.deepStrictEqual(user.username, actor.preferredUsername); - assert.deepStrictEqual(user.inbox, actor.inbox); - }); - - it("Minimum Note", async () => { - const { MockResolver } = await import("./misc/mock-resolver.js"); - const { createNote } = await import( - "../src/remote/activitypub/models/note.js" - ); - - const resolver = new MockResolver(); - resolver._register(actor.id, actor); - resolver._register(post.id, post); - - const note = await createNote(post.id, resolver, true); - - assert.deepStrictEqual(note?.uri, post.id); - assert.deepStrictEqual(note.visibility, "public"); - assert.deepStrictEqual(note.text, post.content); - }); - }); - - describe("Truncate long name", () => { - const host = "https://host1.test"; - const preferredUsername = `${rndstr("A-Z", 4)}${rndstr("a-z", 4)}`; - const actorId = `${host}/users/${preferredUsername.toLowerCase()}`; - - const name = rndstr("0-9a-z", 129); - - const actor = { - "@context": "https://www.w3.org/ns/activitystreams", - id: actorId, - type: "Person", - preferredUsername, - name, - inbox: `${actorId}/inbox`, - outbox: `${actorId}/outbox`, - }; - - it("Actor", async () => { - const { MockResolver } = await import("./misc/mock-resolver.js"); - const { createPerson } = await import( - "../src/remote/activitypub/models/person.js" - ); - - const resolver = new MockResolver(); - resolver._register(actor.id, actor); - - const user = await createPerson(actor.id, resolver); - - assert.deepStrictEqual(user.name, actor.name.substr(0, 128)); - }); - }); -}); diff --git a/packages/backend/test/ap-request.ts b/packages/backend/test/ap-request.ts deleted file mode 100644 index bf77a38532..0000000000 --- a/packages/backend/test/ap-request.ts +++ /dev/null @@ -1,75 +0,0 @@ -import * as assert from "assert"; -import httpSignature from "@peertube/http-signature"; -import { genRsaKeyPair } from "../src/misc/gen-key-pair.js"; -import { - createSignedPost, - createSignedGet, -} from "../src/remote/activitypub/ap-request.js"; - -export const buildParsedSignature = ( - signingString: string, - signature: string, - algorithm: string, -) => { - return { - scheme: "Signature", - params: { - keyId: "KeyID", // dummy, not used for verify - algorithm: algorithm, - headers: ["(request-target)", "date", "host", "digest"], // dummy, not used for verify - signature: signature, - }, - signingString: signingString, - algorithm: algorithm.toUpperCase(), - keyId: "KeyID", // dummy, not used for verify - }; -}; - -describe("ap-request", () => { - it("createSignedPost with verify", async () => { - const keypair = await genRsaKeyPair(); - const key = { keyId: "x", privateKeyPem: keypair.privateKey }; - const url = "https://example.com/inbox"; - const activity = { a: 1 }; - const body = JSON.stringify(activity); - const headers = { - "User-Agent": "UA", - }; - - const req = createSignedPost({ - key, - url, - body, - additionalHeaders: headers, - }); - - const parsed = buildParsedSignature( - req.signingString, - req.signature, - "rsa-sha256", - ); - - const result = httpSignature.verifySignature(parsed, keypair.publicKey); - assert.deepStrictEqual(result, true); - }); - - it("createSignedGet with verify", async () => { - const keypair = await genRsaKeyPair(); - const key = { keyId: "x", privateKeyPem: keypair.privateKey }; - const url = "https://example.com/outbox"; - const headers = { - "User-Agent": "UA", - }; - - const req = createSignedGet({ key, url, additionalHeaders: headers }); - - const parsed = buildParsedSignature( - req.signingString, - req.signature, - "rsa-sha256", - ); - - const result = httpSignature.verifySignature(parsed, keypair.publicKey); - assert.deepStrictEqual(result, true); - }); -}); diff --git a/packages/backend/test/api-visibility.ts b/packages/backend/test/api-visibility.ts deleted file mode 100644 index 0ee4a4d337..0000000000 --- a/packages/backend/test/api-visibility.ts +++ /dev/null @@ -1,535 +0,0 @@ -process.env.NODE_ENV = "test"; - -import * as assert from "assert"; -import * as childProcess from "child_process"; -import { - async, - signup, - request, - post, - startServer, - shutdownServer, -} from "./utils.js"; - -describe("API visibility", () => { - let p: childProcess.ChildProcess; - - before(async () => { - p = await startServer(); - }); - - after(async () => { - await shutdownServer(p); - }); - - describe("Note visibility", async () => { - //#region vars - /** ヒロイン */ - let alice: any; - /** フォロワー */ - let follower: any; - /** 非フォロワー */ - let other: any; - /** 非フォロワーでもリプライやメンションをされた人 */ - let target: any; - /** specified mentionでmentionを飛ばされる人 */ - let target2: any; - - /** public-post */ - let pub: any; - /** home-post */ - let home: any; - /** followers-post */ - let fol: any; - /** specified-post */ - let spe: any; - - /** public-reply to target's post */ - let pubR: any; - /** home-reply to target's post */ - let homeR: any; - /** followers-reply to target's post */ - let folR: any; - /** specified-reply to target's post */ - let speR: any; - - /** public-mention to target */ - let pubM: any; - /** home-mention to target */ - let homeM: any; - /** followers-mention to target */ - let folM: any; - /** specified-mention to target */ - let speM: any; - - /** reply target post */ - let tgt: any; - //#endregion - - const show = async (noteId: any, by: any) => { - return await request( - "/notes/show", - { - noteId, - }, - by, - ); - }; - - before(async () => { - //#region prepare - // signup - alice = await signup({ username: "alice" }); - follower = await signup({ username: "follower" }); - other = await signup({ username: "other" }); - target = await signup({ username: "target" }); - target2 = await signup({ username: "target2" }); - - // follow alice <= follower - await request("/following/create", { userId: alice.id }, follower); - - // normal posts - pub = await post(alice, { text: "x", visibility: "public" }); - home = await post(alice, { text: "x", visibility: "home" }); - fol = await post(alice, { text: "x", visibility: "followers" }); - spe = await post(alice, { - text: "x", - visibility: "specified", - visibleUserIds: [target.id], - }); - - // replies - tgt = await post(target, { text: "y", visibility: "public" }); - pubR = await post(alice, { - text: "x", - replyId: tgt.id, - visibility: "public", - }); - homeR = await post(alice, { - text: "x", - replyId: tgt.id, - visibility: "home", - }); - folR = await post(alice, { - text: "x", - replyId: tgt.id, - visibility: "followers", - }); - speR = await post(alice, { - text: "x", - replyId: tgt.id, - visibility: "specified", - }); - - // mentions - pubM = await post(alice, { - text: "@target x", - replyId: tgt.id, - visibility: "public", - }); - homeM = await post(alice, { - text: "@target x", - replyId: tgt.id, - visibility: "home", - }); - folM = await post(alice, { - text: "@target x", - replyId: tgt.id, - visibility: "followers", - }); - speM = await post(alice, { - text: "@target2 x", - replyId: tgt.id, - visibility: "specified", - }); - //#endregion - }); - - //#region show post - // public - it("[show] public-postを自分が見れる", async(async () => { - const res = await show(pub.id, alice); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] public-postをフォロワーが見れる", async(async () => { - const res = await show(pub.id, follower); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] public-postを非フォロワーが見れる", async(async () => { - const res = await show(pub.id, other); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] public-postを未認証が見れる", async(async () => { - const res = await show(pub.id, null); - assert.strictEqual(res.body.text, "x"); - })); - - // home - it("[show] home-postを自分が見れる", async(async () => { - const res = await show(home.id, alice); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] home-postをフォロワーが見れる", async(async () => { - const res = await show(home.id, follower); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] home-postを非フォロワーが見れる", async(async () => { - const res = await show(home.id, other); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] home-postを未認証が見れる", async(async () => { - const res = await show(home.id, null); - assert.strictEqual(res.body.text, "x"); - })); - - // followers - it("[show] followers-postを自分が見れる", async(async () => { - const res = await show(fol.id, alice); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] followers-postをフォロワーが見れる", async(async () => { - const res = await show(fol.id, follower); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] followers-postを非フォロワーが見れない", async(async () => { - const res = await show(fol.id, other); - assert.strictEqual(res.status, 404); - })); - - it("[show] followers-postを未認証が見れない", async(async () => { - const res = await show(fol.id, null); - assert.strictEqual(res.status, 404); - })); - - // specified - it("[show] specified-postを自分が見れる", async(async () => { - const res = await show(spe.id, alice); - assert.strictEqual(res.status, 404); - })); - - it("[show] specified-postを指定ユーザーが見れる", async(async () => { - const res = await show(spe.id, target); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] specified-postをフォロワーが見れない", async(async () => { - const res = await show(spe.id, follower); - assert.strictEqual(res.status, 404); - })); - - it("[show] specified-postを非フォロワーが見れない", async(async () => { - const res = await show(spe.id, other); - assert.strictEqual(res.status, 404); - })); - - it("[show] specified-postを未認証が見れない", async(async () => { - const res = await show(spe.id, null); - assert.strictEqual(res.status, 404); - })); - //#endregion - - //#region show reply - // public - it("[show] public-replyを自分が見れる", async(async () => { - const res = await show(pubR.id, alice); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] public-replyをされた人が見れる", async(async () => { - const res = await show(pubR.id, target); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] public-replyをフォロワーが見れる", async(async () => { - const res = await show(pubR.id, follower); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] public-replyを非フォロワーが見れる", async(async () => { - const res = await show(pubR.id, other); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] public-replyを未認証が見れる", async(async () => { - const res = await show(pubR.id, null); - assert.strictEqual(res.body.text, "x"); - })); - - // home - it("[show] home-replyを自分が見れる", async(async () => { - const res = await show(homeR.id, alice); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] home-replyをされた人が見れる", async(async () => { - const res = await show(homeR.id, target); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] home-replyをフォロワーが見れる", async(async () => { - const res = await show(homeR.id, follower); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] home-replyを非フォロワーが見れる", async(async () => { - const res = await show(homeR.id, other); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] home-replyを未認証が見れる", async(async () => { - const res = await show(homeR.id, null); - assert.strictEqual(res.body.text, "x"); - })); - - // followers - it("[show] followers-replyを自分が見れる", async(async () => { - const res = await show(folR.id, alice); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] followers-replyを非フォロワーでもリプライされていれば見れる", async(async () => { - const res = await show(folR.id, target); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] followers-replyをフォロワーが見れる", async(async () => { - const res = await show(folR.id, follower); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] followers-replyを非フォロワーが見れない", async(async () => { - const res = await show(folR.id, other); - assert.strictEqual(res.status, 404); - })); - - it("[show] followers-replyを未認証が見れない", async(async () => { - const res = await show(folR.id, null); - assert.strictEqual(res.status, 404); - })); - - // specified - it("[show] specified-replyを自分が見れる", async(async () => { - const res = await show(speR.id, alice); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] specified-replyを指定ユーザーが見れる", async(async () => { - const res = await show(speR.id, target); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] specified-replyをされた人が指定されてなくても見れる", async(async () => { - const res = await show(speR.id, target); - assert.strictEqual(res.body.text, "x"); - })); - - it("[show] specified-replyをフォロワーが見れない", async(async () => { - const res = await show(speR.id, follower); - assert.strictEqual(res.status, 404); - })); - - it("[show] specified-replyを非フォロワーが見れない", async(async () => { - const res = await show(speR.id, other); - assert.strictEqual(res.status, 404); - })); - - it("[show] specified-replyを未認証が見れない", async(async () => { - const res = await show(speR.id, null); - assert.strictEqual(res.status, 404); - })); - //#endregion - - //#region show mention - // public - it("[show] public-mentionを自分が見れる", async(async () => { - const res = await show(pubM.id, alice); - assert.strictEqual(res.body.text, "@target x"); - })); - - it("[show] public-mentionをされた人が見れる", async(async () => { - const res = await show(pubM.id, target); - assert.strictEqual(res.body.text, "@target x"); - })); - - it("[show] public-mentionをフォロワーが見れる", async(async () => { - const res = await show(pubM.id, follower); - assert.strictEqual(res.body.text, "@target x"); - })); - - it("[show] public-mentionを非フォロワーが見れる", async(async () => { - const res = await show(pubM.id, other); - assert.strictEqual(res.body.text, "@target x"); - })); - - it("[show] public-mentionを未認証が見れる", async(async () => { - const res = await show(pubM.id, null); - assert.strictEqual(res.body.text, "@target x"); - })); - - // home - it("[show] home-mentionを自分が見れる", async(async () => { - const res = await show(homeM.id, alice); - assert.strictEqual(res.body.text, "@target x"); - })); - - it("[show] home-mentionをされた人が見れる", async(async () => { - const res = await show(homeM.id, target); - assert.strictEqual(res.body.text, "@target x"); - })); - - it("[show] home-mentionをフォロワーが見れる", async(async () => { - const res = await show(homeM.id, follower); - assert.strictEqual(res.body.text, "@target x"); - })); - - it("[show] home-mentionを非フォロワーが見れる", async(async () => { - const res = await show(homeM.id, other); - assert.strictEqual(res.body.text, "@target x"); - })); - - it("[show] home-mentionを未認証が見れる", async(async () => { - const res = await show(homeM.id, null); - assert.strictEqual(res.body.text, "@target x"); - })); - - // followers - it("[show] followers-mentionを自分が見れる", async(async () => { - const res = await show(folM.id, alice); - assert.strictEqual(res.body.text, "@target x"); - })); - - it("[show] followers-mentionをメンションされていれば非フォロワーでも見れる", async(async () => { - const res = await show(folM.id, target); - assert.strictEqual(res.body.text, "@target x"); - })); - - it("[show] followers-mentionをフォロワーが見れる", async(async () => { - const res = await show(folM.id, follower); - assert.strictEqual(res.body.text, "@target x"); - })); - - it("[show] followers-mentionを非フォロワーが見れない", async(async () => { - const res = await show(folM.id, other); - assert.strictEqual(res.status, 404); - })); - - it("[show] followers-mentionを未認証が見れない", async(async () => { - const res = await show(folM.id, null); - assert.strictEqual(res.status, 404); - })); - - // specified - it("[show] specified-mentionを自分が見れる", async(async () => { - const res = await show(speM.id, alice); - assert.strictEqual(res.body.text, "@target2 x"); - })); - - it("[show] specified-mentionを指定ユーザーが見れる", async(async () => { - const res = await show(speM.id, target); - assert.strictEqual(res.body.text, "@target2 x"); - })); - - it("[show] specified-mentionをされた人が指定されてなかったら見れない", async(async () => { - const res = await show(speM.id, target2); - assert.strictEqual(res.status, 404); - })); - - it("[show] specified-mentionをフォロワーが見れない", async(async () => { - const res = await show(speM.id, follower); - assert.strictEqual(res.status, 404); - })); - - it("[show] specified-mentionを非フォロワーが見れない", async(async () => { - const res = await show(speM.id, other); - assert.strictEqual(res.status, 404); - })); - - it("[show] specified-mentionを未認証が見れない", async(async () => { - const res = await show(speM.id, null); - assert.strictEqual(res.status, 404); - })); - //#endregion - - //#region HTL - it("[HTL] public-post が 自分が見れる", async(async () => { - const res = await request("/notes/timeline", { limit: 100 }, alice); - assert.strictEqual(res.status, 200); - const notes = res.body.filter((n: any) => n.id == pub.id); - assert.strictEqual(notes[0].text, "x"); - })); - - it("[HTL] public-post が 非フォロワーから見れない", async(async () => { - const res = await request("/notes/timeline", { limit: 100 }, other); - assert.strictEqual(res.status, 200); - const notes = res.body.filter((n: any) => n.id == pub.id); - assert.strictEqual(notes.length, 0); - })); - - it("[HTL] followers-post が フォロワーから見れる", async(async () => { - const res = await request("/notes/timeline", { limit: 100 }, follower); - assert.strictEqual(res.status, 200); - const notes = res.body.filter((n: any) => n.id == fol.id); - assert.strictEqual(notes[0].text, "x"); - })); - //#endregion - - //#region RTL - it("[replies] followers-reply が フォロワーから見れる", async(async () => { - const res = await request( - "/notes/replies", - { noteId: tgt.id, limit: 100 }, - follower, - ); - assert.strictEqual(res.status, 200); - const notes = res.body.filter((n: any) => n.id == folR.id); - assert.strictEqual(notes[0].text, "x"); - })); - - it("[replies] followers-reply が 非フォロワー (リプライ先ではない) から見れない", async(async () => { - const res = await request( - "/notes/replies", - { noteId: tgt.id, limit: 100 }, - other, - ); - assert.strictEqual(res.status, 200); - const notes = res.body.filter((n: any) => n.id == folR.id); - assert.strictEqual(notes.length, 0); - })); - - it("[replies] followers-reply が 非フォロワー (リプライ先である) から見れる", async(async () => { - const res = await request( - "/notes/replies", - { noteId: tgt.id, limit: 100 }, - target, - ); - assert.strictEqual(res.status, 200); - const notes = res.body.filter((n: any) => n.id == folR.id); - assert.strictEqual(notes[0].text, "x"); - })); - //#endregion - - //#region MTL - it("[mentions] followers-reply が 非フォロワー (リプライ先である) から見れる", async(async () => { - const res = await request("/notes/mentions", { limit: 100 }, target); - assert.strictEqual(res.status, 200); - const notes = res.body.filter((n: any) => n.id == folR.id); - assert.strictEqual(notes[0].text, "x"); - })); - - it("[mentions] followers-mention が 非フォロワー (メンション先である) から見れる", async(async () => { - const res = await request("/notes/mentions", { limit: 100 }, target); - assert.strictEqual(res.status, 200); - const notes = res.body.filter((n: any) => n.id == folM.id); - assert.strictEqual(notes[0].text, "@target x"); - })); - //#endregion - }); -}); diff --git a/packages/backend/test/api.ts b/packages/backend/test/api.ts deleted file mode 100644 index 19a754552c..0000000000 --- a/packages/backend/test/api.ts +++ /dev/null @@ -1,92 +0,0 @@ -process.env.NODE_ENV = "test"; - -import * as assert from "assert"; -import * as childProcess from "child_process"; -import { - async, - signup, - request, - post, - react, - uploadFile, - startServer, - shutdownServer, -} from "./utils.js"; - -describe("API", () => { - let p: childProcess.ChildProcess; - let alice: any; - let bob: any; - let carol: any; - - before(async () => { - p = await startServer(); - alice = await signup({ username: "alice" }); - bob = await signup({ username: "bob" }); - carol = await signup({ username: "carol" }); - }); - - after(async () => { - await shutdownServer(p); - }); - - describe("General validation", () => { - it("wrong type", async(async () => { - const res = await request("/test", { - required: true, - string: 42, - }); - assert.strictEqual(res.status, 400); - })); - - it("missing require param", async(async () => { - const res = await request("/test", { - string: "a", - }); - assert.strictEqual(res.status, 400); - })); - - it("invalid misskey:id (empty string)", async(async () => { - const res = await request("/test", { - required: true, - id: "", - }); - assert.strictEqual(res.status, 400); - })); - - it("valid misskey:id", async(async () => { - const res = await request("/test", { - required: true, - id: "8wvhjghbxu", - }); - assert.strictEqual(res.status, 200); - })); - - it("default value", async(async () => { - const res = await request("/test", { - required: true, - string: "a", - }); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.body.default, "hello"); - })); - - it("can set null even if it has default value", async(async () => { - const res = await request("/test", { - required: true, - nullableDefault: null, - }); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.body.nullableDefault, null); - })); - - it("cannot set undefined if it has default value", async(async () => { - const res = await request("/test", { - required: true, - nullableDefault: undefined, - }); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.body.nullableDefault, "hello"); - })); - }); -}); diff --git a/packages/backend/test/block.ts b/packages/backend/test/block.ts deleted file mode 100644 index 08192e4869..0000000000 --- a/packages/backend/test/block.ts +++ /dev/null @@ -1,129 +0,0 @@ -process.env.NODE_ENV = "test"; - -import * as assert from "assert"; -import * as childProcess from "child_process"; -import { - async, - signup, - request, - post, - startServer, - shutdownServer, -} from "./utils.js"; - -describe("Block", () => { - let p: childProcess.ChildProcess; - - // alice blocks bob - let alice: any; - let bob: any; - let carol: any; - - before(async () => { - p = await startServer(); - alice = await signup({ username: "alice" }); - bob = await signup({ username: "bob" }); - carol = await signup({ username: "carol" }); - }); - - after(async () => { - await shutdownServer(p); - }); - - it("Block作成", async(async () => { - const res = await request( - "/blocking/create", - { - userId: bob.id, - }, - alice, - ); - - assert.strictEqual(res.status, 200); - })); - - it("ブロックされているユーザーをフォローできない", async(async () => { - const res = await request("/following/create", { userId: alice.id }, bob); - - assert.strictEqual(res.status, 400); - assert.strictEqual( - res.body.error.id, - "c4ab57cc-4e41-45e9-bfd9-584f61e35ce0", - ); - })); - - it("ブロックされているユーザーにリアクションできない", async(async () => { - const note = await post(alice, { text: "hello" }); - - const res = await request( - "/notes/reactions/create", - { noteId: note.id, reaction: "👍" }, - bob, - ); - - assert.strictEqual(res.status, 400); - assert.strictEqual( - res.body.error.id, - "20ef5475-9f38-4e4c-bd33-de6d979498ec", - ); - })); - - it("ブロックされているユーザーに返信できない", async(async () => { - const note = await post(alice, { text: "hello" }); - - const res = await request( - "/notes/create", - { replyId: note.id, text: "yo" }, - bob, - ); - - assert.strictEqual(res.status, 400); - assert.strictEqual( - res.body.error.id, - "b390d7e1-8a5e-46ed-b625-06271cafd3d3", - ); - })); - - it("ブロックされているユーザーのノートをRenoteできない", async(async () => { - const note = await post(alice, { text: "hello" }); - - const res = await request( - "/notes/create", - { renoteId: note.id, text: "yo" }, - bob, - ); - - assert.strictEqual(res.status, 400); - assert.strictEqual( - res.body.error.id, - "b390d7e1-8a5e-46ed-b625-06271cafd3d3", - ); - })); - - // TODO: ユーザーリストに入れられないテスト - - // TODO: ユーザーリストから除外されるテスト - - it("タイムライン(LTL)にブロックされているユーザーの投稿が含まれない", async(async () => { - const aliceNote = await post(alice); - const bobNote = await post(bob); - const carolNote = await post(carol); - - const res = await request("/notes/local-timeline", {}, bob); - - assert.strictEqual(res.status, 200); - assert.strictEqual(Array.isArray(res.body), true); - assert.strictEqual( - res.body.some((note: any) => note.id === aliceNote.id), - false, - ); - assert.strictEqual( - res.body.some((note: any) => note.id === bobNote.id), - true, - ); - assert.strictEqual( - res.body.some((note: any) => note.id === carolNote.id), - true, - ); - })); -}); diff --git a/packages/backend/test/chart.ts b/packages/backend/test/chart.ts deleted file mode 100644 index e194c6c195..0000000000 --- a/packages/backend/test/chart.ts +++ /dev/null @@ -1,575 +0,0 @@ -process.env.NODE_ENV = "test"; - -import * as assert from "assert"; -import * as lolex from "@sinonjs/fake-timers"; -import TestChart from "../src/services/chart/charts/test.js"; -import TestGroupedChart from "../src/services/chart/charts/test-grouped.js"; -import TestUniqueChart from "../src/services/chart/charts/test-unique.js"; -import TestIntersectionChart from "../src/services/chart/charts/test-intersection.js"; -import { initDb } from "../src/db/postgre.js"; - -describe("Chart", () => { - let testChart: TestChart; - let testGroupedChart: TestGroupedChart; - let testUniqueChart: TestUniqueChart; - let testIntersectionChart: TestIntersectionChart; - let clock: lolex.InstalledClock; - - beforeEach(async () => { - await initDb(true); - - testChart = new TestChart(); - testGroupedChart = new TestGroupedChart(); - testUniqueChart = new TestUniqueChart(); - testIntersectionChart = new TestIntersectionChart(); - - clock = lolex.install({ - now: new Date(Date.UTC(2000, 0, 1, 0, 0, 0)), - shouldClearNativeTimers: true, - }); - }); - - afterEach(() => { - clock.uninstall(); - }); - - it("Can updates", async () => { - await testChart.increment(); - await testChart.save(); - - const chartHours = await testChart.getChart("hour", 3, null); - const chartDays = await testChart.getChart("day", 3, null); - - assert.deepStrictEqual(chartHours, { - foo: { - dec: [0, 0, 0], - inc: [1, 0, 0], - total: [1, 0, 0], - }, - }); - - assert.deepStrictEqual(chartDays, { - foo: { - dec: [0, 0, 0], - inc: [1, 0, 0], - total: [1, 0, 0], - }, - }); - }); - - it("Can updates (dec)", async () => { - await testChart.decrement(); - await testChart.save(); - - const chartHours = await testChart.getChart("hour", 3, null); - const chartDays = await testChart.getChart("day", 3, null); - - assert.deepStrictEqual(chartHours, { - foo: { - dec: [1, 0, 0], - inc: [0, 0, 0], - total: [-1, 0, 0], - }, - }); - - assert.deepStrictEqual(chartDays, { - foo: { - dec: [1, 0, 0], - inc: [0, 0, 0], - total: [-1, 0, 0], - }, - }); - }); - - it("Empty chart", async () => { - const chartHours = await testChart.getChart("hour", 3, null); - const chartDays = await testChart.getChart("day", 3, null); - - assert.deepStrictEqual(chartHours, { - foo: { - dec: [0, 0, 0], - inc: [0, 0, 0], - total: [0, 0, 0], - }, - }); - - assert.deepStrictEqual(chartDays, { - foo: { - dec: [0, 0, 0], - inc: [0, 0, 0], - total: [0, 0, 0], - }, - }); - }); - - it("Can updates at multiple times at same time", async () => { - await testChart.increment(); - await testChart.increment(); - await testChart.increment(); - await testChart.save(); - - const chartHours = await testChart.getChart("hour", 3, null); - const chartDays = await testChart.getChart("day", 3, null); - - assert.deepStrictEqual(chartHours, { - foo: { - dec: [0, 0, 0], - inc: [3, 0, 0], - total: [3, 0, 0], - }, - }); - - assert.deepStrictEqual(chartDays, { - foo: { - dec: [0, 0, 0], - inc: [3, 0, 0], - total: [3, 0, 0], - }, - }); - }); - - it("複数回saveされてもデータの更新は一度だけ", async () => { - await testChart.increment(); - await testChart.save(); - await testChart.save(); - await testChart.save(); - - const chartHours = await testChart.getChart("hour", 3, null); - const chartDays = await testChart.getChart("day", 3, null); - - assert.deepStrictEqual(chartHours, { - foo: { - dec: [0, 0, 0], - inc: [1, 0, 0], - total: [1, 0, 0], - }, - }); - - assert.deepStrictEqual(chartDays, { - foo: { - dec: [0, 0, 0], - inc: [1, 0, 0], - total: [1, 0, 0], - }, - }); - }); - - it("Can updates at different times", async () => { - await testChart.increment(); - await testChart.save(); - - clock.tick("01:00:00"); - - await testChart.increment(); - await testChart.save(); - - const chartHours = await testChart.getChart("hour", 3, null); - const chartDays = await testChart.getChart("day", 3, null); - - assert.deepStrictEqual(chartHours, { - foo: { - dec: [0, 0, 0], - inc: [1, 1, 0], - total: [2, 1, 0], - }, - }); - - assert.deepStrictEqual(chartDays, { - foo: { - dec: [0, 0, 0], - inc: [2, 0, 0], - total: [2, 0, 0], - }, - }); - }); - - // 仕様上はこうなってほしいけど、実装は難しそうなのでskip - /* - it('Can updates at different times without save', async () => { - await testChart.increment(); - - clock.tick('01:00:00'); - - await testChart.increment(); - await testChart.save(); - - const chartHours = await testChart.getChart('hour', 3, null); - const chartDays = await testChart.getChart('day', 3, null); - - assert.deepStrictEqual(chartHours, { - foo: { - dec: [0, 0, 0], - inc: [1, 1, 0], - total: [2, 1, 0] - }, - }); - - assert.deepStrictEqual(chartDays, { - foo: { - dec: [0, 0, 0], - inc: [2, 0, 0], - total: [2, 0, 0] - }, - }); - }); - */ - - it("Can padding", async () => { - await testChart.increment(); - await testChart.save(); - - clock.tick("02:00:00"); - - await testChart.increment(); - await testChart.save(); - - const chartHours = await testChart.getChart("hour", 3, null); - const chartDays = await testChart.getChart("day", 3, null); - - assert.deepStrictEqual(chartHours, { - foo: { - dec: [0, 0, 0], - inc: [1, 0, 1], - total: [2, 1, 1], - }, - }); - - assert.deepStrictEqual(chartDays, { - foo: { - dec: [0, 0, 0], - inc: [2, 0, 0], - total: [2, 0, 0], - }, - }); - }); - - // 要求された範囲にログがひとつもない場合でもパディングできる - it("Can padding from past range", async () => { - await testChart.increment(); - await testChart.save(); - - clock.tick("05:00:00"); - - const chartHours = await testChart.getChart("hour", 3, null); - const chartDays = await testChart.getChart("day", 3, null); - - assert.deepStrictEqual(chartHours, { - foo: { - dec: [0, 0, 0], - inc: [0, 0, 0], - total: [1, 1, 1], - }, - }); - - assert.deepStrictEqual(chartDays, { - foo: { - dec: [0, 0, 0], - inc: [1, 0, 0], - total: [1, 0, 0], - }, - }); - }); - - // 要求された範囲の最も古い箇所に位置するログが存在しない場合でもパディングできる - // Issue #3190 - it("Can padding from past range 2", async () => { - await testChart.increment(); - await testChart.save(); - - clock.tick("05:00:00"); - - await testChart.increment(); - await testChart.save(); - - const chartHours = await testChart.getChart("hour", 3, null); - const chartDays = await testChart.getChart("day", 3, null); - - assert.deepStrictEqual(chartHours, { - foo: { - dec: [0, 0, 0], - inc: [1, 0, 0], - total: [2, 1, 1], - }, - }); - - assert.deepStrictEqual(chartDays, { - foo: { - dec: [0, 0, 0], - inc: [2, 0, 0], - total: [2, 0, 0], - }, - }); - }); - - it("Can specify offset", async () => { - await testChart.increment(); - await testChart.save(); - - clock.tick("01:00:00"); - - await testChart.increment(); - await testChart.save(); - - const chartHours = await testChart.getChart( - "hour", - 3, - new Date(Date.UTC(2000, 0, 1, 0, 0, 0)), - ); - const chartDays = await testChart.getChart( - "day", - 3, - new Date(Date.UTC(2000, 0, 1, 0, 0, 0)), - ); - - assert.deepStrictEqual(chartHours, { - foo: { - dec: [0, 0, 0], - inc: [1, 0, 0], - total: [1, 0, 0], - }, - }); - - assert.deepStrictEqual(chartDays, { - foo: { - dec: [0, 0, 0], - inc: [2, 0, 0], - total: [2, 0, 0], - }, - }); - }); - - it("Can specify offset (floor time)", async () => { - clock.tick("00:30:00"); - - await testChart.increment(); - await testChart.save(); - - clock.tick("01:30:00"); - - await testChart.increment(); - await testChart.save(); - - const chartHours = await testChart.getChart( - "hour", - 3, - new Date(Date.UTC(2000, 0, 1, 0, 0, 0)), - ); - const chartDays = await testChart.getChart( - "day", - 3, - new Date(Date.UTC(2000, 0, 1, 0, 0, 0)), - ); - - assert.deepStrictEqual(chartHours, { - foo: { - dec: [0, 0, 0], - inc: [1, 0, 0], - total: [1, 0, 0], - }, - }); - - assert.deepStrictEqual(chartDays, { - foo: { - dec: [0, 0, 0], - inc: [2, 0, 0], - total: [2, 0, 0], - }, - }); - }); - - describe("Grouped", () => { - it("Can updates", async () => { - await testGroupedChart.increment("alice"); - await testGroupedChart.save(); - - const aliceChartHours = await testGroupedChart.getChart( - "hour", - 3, - null, - "alice", - ); - const aliceChartDays = await testGroupedChart.getChart( - "day", - 3, - null, - "alice", - ); - const bobChartHours = await testGroupedChart.getChart( - "hour", - 3, - null, - "bob", - ); - const bobChartDays = await testGroupedChart.getChart( - "day", - 3, - null, - "bob", - ); - - assert.deepStrictEqual(aliceChartHours, { - foo: { - dec: [0, 0, 0], - inc: [1, 0, 0], - total: [1, 0, 0], - }, - }); - - assert.deepStrictEqual(aliceChartDays, { - foo: { - dec: [0, 0, 0], - inc: [1, 0, 0], - total: [1, 0, 0], - }, - }); - - assert.deepStrictEqual(bobChartHours, { - foo: { - dec: [0, 0, 0], - inc: [0, 0, 0], - total: [0, 0, 0], - }, - }); - - assert.deepStrictEqual(bobChartDays, { - foo: { - dec: [0, 0, 0], - inc: [0, 0, 0], - total: [0, 0, 0], - }, - }); - }); - }); - - describe("Unique increment", () => { - it("Can updates", async () => { - await testUniqueChart.uniqueIncrement("alice"); - await testUniqueChart.uniqueIncrement("alice"); - await testUniqueChart.uniqueIncrement("bob"); - await testUniqueChart.save(); - - const chartHours = await testUniqueChart.getChart("hour", 3, null); - const chartDays = await testUniqueChart.getChart("day", 3, null); - - assert.deepStrictEqual(chartHours, { - foo: [2, 0, 0], - }); - - assert.deepStrictEqual(chartDays, { - foo: [2, 0, 0], - }); - }); - - describe("Intersection", () => { - it("条件が満たされていない場合はカウントされない", async () => { - await testIntersectionChart.addA("alice"); - await testIntersectionChart.addA("bob"); - await testIntersectionChart.addB("carol"); - await testIntersectionChart.save(); - - const chartHours = await testIntersectionChart.getChart( - "hour", - 3, - null, - ); - const chartDays = await testIntersectionChart.getChart("day", 3, null); - - assert.deepStrictEqual(chartHours, { - a: [2, 0, 0], - b: [1, 0, 0], - aAndB: [0, 0, 0], - }); - - assert.deepStrictEqual(chartDays, { - a: [2, 0, 0], - b: [1, 0, 0], - aAndB: [0, 0, 0], - }); - }); - - it("条件が満たされている場合にカウントされる", async () => { - await testIntersectionChart.addA("alice"); - await testIntersectionChart.addA("bob"); - await testIntersectionChart.addB("carol"); - await testIntersectionChart.addB("alice"); - await testIntersectionChart.save(); - - const chartHours = await testIntersectionChart.getChart( - "hour", - 3, - null, - ); - const chartDays = await testIntersectionChart.getChart("day", 3, null); - - assert.deepStrictEqual(chartHours, { - a: [2, 0, 0], - b: [2, 0, 0], - aAndB: [1, 0, 0], - }); - - assert.deepStrictEqual(chartDays, { - a: [2, 0, 0], - b: [2, 0, 0], - aAndB: [1, 0, 0], - }); - }); - }); - }); - - describe("Resync", () => { - it("Can resync", async () => { - testChart.total = 1; - - await testChart.resync(); - - const chartHours = await testChart.getChart("hour", 3, null); - const chartDays = await testChart.getChart("day", 3, null); - - assert.deepStrictEqual(chartHours, { - foo: { - dec: [0, 0, 0], - inc: [0, 0, 0], - total: [1, 0, 0], - }, - }); - - assert.deepStrictEqual(chartDays, { - foo: { - dec: [0, 0, 0], - inc: [0, 0, 0], - total: [1, 0, 0], - }, - }); - }); - - it("Can resync (2)", async () => { - await testChart.increment(); - await testChart.save(); - - clock.tick("01:00:00"); - - testChart.total = 100; - - await testChart.resync(); - - const chartHours = await testChart.getChart("hour", 3, null); - const chartDays = await testChart.getChart("day", 3, null); - - assert.deepStrictEqual(chartHours, { - foo: { - dec: [0, 0, 0], - inc: [0, 1, 0], - total: [100, 1, 0], - }, - }); - - assert.deepStrictEqual(chartDays, { - foo: { - dec: [0, 0, 0], - inc: [1, 0, 0], - total: [100, 0, 0], - }, - }); - }); - }); -}); diff --git a/packages/backend/test/docker-compose.yml b/packages/backend/test/docker-compose.yml deleted file mode 100644 index 5f95bec4c0..0000000000 --- a/packages/backend/test/docker-compose.yml +++ /dev/null @@ -1,15 +0,0 @@ -version: "3" - -services: - redistest: - image: redis:6 - ports: - - "127.0.0.1:56312:6379" - - dbtest: - image: postgres:13 - ports: - - "127.0.0.1:54312:5432" - environment: - POSTGRES_DB: "test-misskey" - POSTGRES_HOST_AUTH_METHOD: trust diff --git a/packages/backend/test/endpoints.ts b/packages/backend/test/endpoints.ts deleted file mode 100644 index 2aedc25f2c..0000000000 --- a/packages/backend/test/endpoints.ts +++ /dev/null @@ -1,865 +0,0 @@ -/* -process.env.NODE_ENV = 'test'; - -import * as assert from 'assert'; -import * as childProcess from 'child_process'; -import { async, signup, request, post, react, uploadFile, startServer, shutdownServer } from './utils.js'; - -describe('API: Endpoints', () => { - let p: childProcess.ChildProcess; - let alice: any; - let bob: any; - let carol: any; - - before(async () => { - p = await startServer(); - alice = await signup({ username: 'alice' }); - bob = await signup({ username: 'bob' }); - carol = await signup({ username: 'carol' }); - }); - - after(async () => { - await shutdownServer(p); - }); - - describe('signup', () => { - it('不正なユーザー名でアカウントが作成できない', async(async () => { - const res = await request('/signup', { - username: 'test.', - password: 'test' - }); - assert.strictEqual(res.status, 400); - })); - - it('空のパスワードでアカウントが作成できない', async(async () => { - const res = await request('/signup', { - username: 'test', - password: '' - }); - assert.strictEqual(res.status, 400); - })); - - it('正しくアカウントが作成できる', async(async () => { - const me = { - username: 'test1', - password: 'test1' - }; - - const res = await request('/signup', me); - - assert.strictEqual(res.status, 200); - assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.username, me.username); - })); - - it('同じユーザー名のアカウントは作成できない', async(async () => { - await signup({ - username: 'test2' - }); - - const res = await request('/signup', { - username: 'test2', - password: 'test2' - }); - - assert.strictEqual(res.status, 400); - })); - }); - - describe('signin', () => { - it('間違ったパスワードでサインインできない', async(async () => { - await signup({ - username: 'test3', - password: 'foo' - }); - - const res = await request('/signin', { - username: 'test3', - password: 'bar' - }); - - assert.strictEqual(res.status, 403); - })); - - it('クエリをインジェクションできない', async(async () => { - await signup({ - username: 'test4' - }); - - const res = await request('/signin', { - username: 'test4', - password: { - $gt: '' - } - }); - - assert.strictEqual(res.status, 400); - })); - - it('正しい情報でサインインできる', async(async () => { - await signup({ - username: 'test5', - password: 'foo' - }); - - const res = await request('/signin', { - username: 'test5', - password: 'foo' - }); - - assert.strictEqual(res.status, 200); - })); - }); - - describe('i/update', () => { - it('アカウント設定を更新できる', async(async () => { - const myName = '大室櫻子'; - const myLocation = '七森中'; - const myBirthday = '2000-09-07'; - - const res = await request('/i/update', { - name: myName, - location: myLocation, - birthday: myBirthday - }, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.name, myName); - assert.strictEqual(res.body.location, myLocation); - assert.strictEqual(res.body.birthday, myBirthday); - })); - - it('名前を空白にできない', async(async () => { - const res = await request('/i/update', { - name: ' ' - }, alice); - assert.strictEqual(res.status, 400); - })); - - it('誕生日の設定を削除できる', async(async () => { - await request('/i/update', { - birthday: '2000-09-07' - }, alice); - - const res = await request('/i/update', { - birthday: null - }, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.birthday, null); - })); - - it('不正な誕生日の形式で怒られる', async(async () => { - const res = await request('/i/update', { - birthday: '2000/09/07' - }, alice); - assert.strictEqual(res.status, 400); - })); - }); - - describe('users/show', () => { - it('ユーザーが取得できる', async(async () => { - const res = await request('/users/show', { - userId: alice.id - }, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.id, alice.id); - })); - - it('ユーザーが存在しなかったら怒る', async(async () => { - const res = await request('/users/show', { - userId: '000000000000000000000000' - }); - assert.strictEqual(res.status, 400); - })); - - it('間違ったIDで怒られる', async(async () => { - const res = await request('/users/show', { - userId: 'kyoppie' - }); - assert.strictEqual(res.status, 400); - })); - }); - - describe('notes/show', () => { - it('投稿が取得できる', async(async () => { - const myPost = await post(alice, { - text: 'test' - }); - - const res = await request('/notes/show', { - noteId: myPost.id - }, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.id, myPost.id); - assert.strictEqual(res.body.text, myPost.text); - })); - - it('投稿が存在しなかったら怒る', async(async () => { - const res = await request('/notes/show', { - noteId: '000000000000000000000000' - }); - assert.strictEqual(res.status, 400); - })); - - it('間違ったIDで怒られる', async(async () => { - const res = await request('/notes/show', { - noteId: 'kyoppie' - }); - assert.strictEqual(res.status, 400); - })); - }); - - describe('notes/reactions/create', () => { - it('リアクションできる', async(async () => { - const bobPost = await post(bob); - - const alice = await signup({ username: 'alice' }); - const res = await request('/notes/reactions/create', { - noteId: bobPost.id, - reaction: '🚀', - }, alice); - - assert.strictEqual(res.status, 204); - - const resNote = await request('/notes/show', { - noteId: bobPost.id, - }, alice); - - assert.strictEqual(resNote.status, 200); - assert.strictEqual(resNote.body.reactions['🚀'], [alice.id]); - })); - - it('自分の投稿にもリアクションできる', async(async () => { - const myPost = await post(alice); - - const res = await request('/notes/reactions/create', { - noteId: myPost.id, - reaction: '🚀', - }, alice); - - assert.strictEqual(res.status, 204); - })); - - it('二重にリアクションできない', async(async () => { - const bobPost = await post(bob); - - await react(alice, bobPost, 'like'); - - const res = await request('/notes/reactions/create', { - noteId: bobPost.id, - reaction: '🚀', - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('存在しない投稿にはリアクションできない', async(async () => { - const res = await request('/notes/reactions/create', { - noteId: '000000000000000000000000', - reaction: '🚀', - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('空のパラメータで怒られる', async(async () => { - const res = await request('/notes/reactions/create', {}, alice); - - assert.strictEqual(res.status, 400); - })); - - it('間違ったIDで怒られる', async(async () => { - const res = await request('/notes/reactions/create', { - noteId: 'kyoppie', - reaction: '🚀', - }, alice); - - assert.strictEqual(res.status, 400); - })); - }); - - describe('following/create', () => { - it('フォローできる', async(async () => { - const res = await request('/following/create', { - userId: alice.id - }, bob); - - assert.strictEqual(res.status, 200); - })); - - it('既にフォローしている場合は怒る', async(async () => { - const res = await request('/following/create', { - userId: alice.id - }, bob); - - assert.strictEqual(res.status, 400); - })); - - it('存在しないユーザーはフォローできない', async(async () => { - const res = await request('/following/create', { - userId: '000000000000000000000000' - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('自分自身はフォローできない', async(async () => { - const res = await request('/following/create', { - userId: alice.id - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('空のパラメータで怒られる', async(async () => { - const res = await request('/following/create', {}, alice); - - assert.strictEqual(res.status, 400); - })); - - it('間違ったIDで怒られる', async(async () => { - const res = await request('/following/create', { - userId: 'foo' - }, alice); - - assert.strictEqual(res.status, 400); - })); - }); - - describe('following/delete', () => { - it('フォロー解除できる', async(async () => { - await request('/following/create', { - userId: alice.id - }, bob); - - const res = await request('/following/delete', { - userId: alice.id - }, bob); - - assert.strictEqual(res.status, 200); - })); - - it('フォローしていない場合は怒る', async(async () => { - const res = await request('/following/delete', { - userId: alice.id - }, bob); - - assert.strictEqual(res.status, 400); - })); - - it('存在しないユーザーはフォロー解除できない', async(async () => { - const res = await request('/following/delete', { - userId: '000000000000000000000000' - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('自分自身はフォロー解除できない', async(async () => { - const res = await request('/following/delete', { - userId: alice.id - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('空のパラメータで怒られる', async(async () => { - const res = await request('/following/delete', {}, alice); - - assert.strictEqual(res.status, 400); - })); - - it('間違ったIDで怒られる', async(async () => { - const res = await request('/following/delete', { - userId: 'kyoppie' - }, alice); - - assert.strictEqual(res.status, 400); - })); - }); - - describe('drive', () => { - it('ドライブ情報を取得できる', async(async () => { - await uploadFile({ - userId: alice.id, - size: 256 - }); - await uploadFile({ - userId: alice.id, - size: 512 - }); - await uploadFile({ - userId: alice.id, - size: 1024 - }); - const res = await request('/drive', {}, alice); - assert.strictEqual(res.status, 200); - assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - expect(res.body).have.property('usage').eql(1792); - })); - }); - - describe('drive/files/create', () => { - it('ファイルを作成できる', async(async () => { - const res = await uploadFile(alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.name, 'Lenna.png'); - })); - - it('ファイルに名前を付けられる', async(async () => { - const res = await assert.request(server) - .post('/drive/files/create') - .field('i', alice.token) - .field('name', 'Belmond.png') - .attach('file', fs.readFileSync(__dirname + '/resources/Lenna.png'), 'Lenna.png'); - - expect(res).have.status(200); - expect(res.body).be.a('object'); - expect(res.body).have.property('name').eql('Belmond.png'); - })); - - it('ファイル無しで怒られる', async(async () => { - const res = await request('/drive/files/create', {}, alice); - - assert.strictEqual(res.status, 400); - })); - - it('SVGファイルを作成できる', async(async () => { - const res = await uploadFile(alice, __dirname + '/resources/image.svg'); - - assert.strictEqual(res.status, 200); - assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.name, 'image.svg'); - assert.strictEqual(res.body.type, 'image/svg+xml'); - })); - }); - - describe('drive/files/update', () => { - it('名前を更新できる', async(async () => { - const file = await uploadFile(alice); - const newName = 'いちごパスタ.png'; - - const res = await request('/drive/files/update', { - fileId: file.id, - name: newName - }, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.name, newName); - })); - - it('他人のファイルは更新できない', async(async () => { - const file = await uploadFile(bob); - - const res = await request('/drive/files/update', { - fileId: file.id, - name: 'いちごパスタ.png' - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('親フォルダを更新できる', async(async () => { - const file = await uploadFile(alice); - const folder = (await request('/drive/folders/create', { - name: 'test' - }, alice)).body; - - const res = await request('/drive/files/update', { - fileId: file.id, - folderId: folder.id - }, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.folderId, folder.id); - })); - - it('親フォルダを無しにできる', async(async () => { - const file = await uploadFile(alice); - - const folder = (await request('/drive/folders/create', { - name: 'test' - }, alice)).body; - - await request('/drive/files/update', { - fileId: file.id, - folderId: folder.id - }, alice); - - const res = await request('/drive/files/update', { - fileId: file.id, - folderId: null - }, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.folderId, null); - })); - - it('他人のフォルダには入れられない', async(async () => { - const file = await uploadFile(alice); - const folder = (await request('/drive/folders/create', { - name: 'test' - }, bob)).body; - - const res = await request('/drive/files/update', { - fileId: file.id, - folderId: folder.id - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('存在しないフォルダで怒られる', async(async () => { - const file = await uploadFile(alice); - - const res = await request('/drive/files/update', { - fileId: file.id, - folderId: '000000000000000000000000' - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('不正なフォルダIDで怒られる', async(async () => { - const file = await uploadFile(alice); - - const res = await request('/drive/files/update', { - fileId: file.id, - folderId: 'foo' - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('ファイルが存在しなかったら怒る', async(async () => { - const res = await request('/drive/files/update', { - fileId: '000000000000000000000000', - name: 'いちごパスタ.png' - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('間違ったIDで怒られる', async(async () => { - const res = await request('/drive/files/update', { - fileId: 'kyoppie', - name: 'いちごパスタ.png' - }, alice); - - assert.strictEqual(res.status, 400); - })); - }); - - describe('drive/folders/create', () => { - it('フォルダを作成できる', async(async () => { - const res = await request('/drive/folders/create', { - name: 'test' - }, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.name, 'test'); - })); - }); - - describe('drive/folders/update', () => { - it('名前を更新できる', async(async () => { - const folder = (await request('/drive/folders/create', { - name: 'test' - }, alice)).body; - - const res = await request('/drive/folders/update', { - folderId: folder.id, - name: 'new name' - }, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.name, 'new name'); - })); - - it('他人のフォルダを更新できない', async(async () => { - const folder = (await request('/drive/folders/create', { - name: 'test' - }, bob)).body; - - const res = await request('/drive/folders/update', { - folderId: folder.id, - name: 'new name' - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('親フォルダを更新できる', async(async () => { - const folder = (await request('/drive/folders/create', { - name: 'test' - }, alice)).body; - const parentFolder = (await request('/drive/folders/create', { - name: 'parent' - }, alice)).body; - - const res = await request('/drive/folders/update', { - folderId: folder.id, - parentId: parentFolder.id - }, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.parentId, parentFolder.id); - })); - - it('親フォルダを無しに更新できる', async(async () => { - const folder = (await request('/drive/folders/create', { - name: 'test' - }, alice)).body; - const parentFolder = (await request('/drive/folders/create', { - name: 'parent' - }, alice)).body; - await request('/drive/folders/update', { - folderId: folder.id, - parentId: parentFolder.id - }, alice); - - const res = await request('/drive/folders/update', { - folderId: folder.id, - parentId: null - }, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.parentId, null); - })); - - it('他人のフォルダを親フォルダに設定できない', async(async () => { - const folder = (await request('/drive/folders/create', { - name: 'test' - }, alice)).body; - const parentFolder = (await request('/drive/folders/create', { - name: 'parent' - }, bob)).body; - - const res = await request('/drive/folders/update', { - folderId: folder.id, - parentId: parentFolder.id - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('フォルダが循環するような構造にできない', async(async () => { - const folder = (await request('/drive/folders/create', { - name: 'test' - }, alice)).body; - const parentFolder = (await request('/drive/folders/create', { - name: 'parent' - }, alice)).body; - await request('/drive/folders/update', { - folderId: parentFolder.id, - parentId: folder.id - }, alice); - - const res = await request('/drive/folders/update', { - folderId: folder.id, - parentId: parentFolder.id - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('フォルダが循環するような構造にできない(再帰的)', async(async () => { - const folderA = (await request('/drive/folders/create', { - name: 'test' - }, alice)).body; - const folderB = (await request('/drive/folders/create', { - name: 'test' - }, alice)).body; - const folderC = (await request('/drive/folders/create', { - name: 'test' - }, alice)).body; - await request('/drive/folders/update', { - folderId: folderB.id, - parentId: folderA.id - }, alice); - await request('/drive/folders/update', { - folderId: folderC.id, - parentId: folderB.id - }, alice); - - const res = await request('/drive/folders/update', { - folderId: folderA.id, - parentId: folderC.id - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('フォルダが循環するような構造にできない(自身)', async(async () => { - const folderA = (await request('/drive/folders/create', { - name: 'test' - }, alice)).body; - - const res = await request('/drive/folders/update', { - folderId: folderA.id, - parentId: folderA.id - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('存在しない親フォルダを設定できない', async(async () => { - const folder = (await request('/drive/folders/create', { - name: 'test' - }, alice)).body; - - const res = await request('/drive/folders/update', { - folderId: folder.id, - parentId: '000000000000000000000000' - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('不正な親フォルダIDで怒られる', async(async () => { - const folder = (await request('/drive/folders/create', { - name: 'test' - }, alice)).body; - - const res = await request('/drive/folders/update', { - folderId: folder.id, - parentId: 'foo' - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('存在しないフォルダを更新できない', async(async () => { - const res = await request('/drive/folders/update', { - folderId: '000000000000000000000000' - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('不正なフォルダIDで怒られる', async(async () => { - const res = await request('/drive/folders/update', { - folderId: 'foo' - }, alice); - - assert.strictEqual(res.status, 400); - })); - }); - - describe('messaging/messages/create', () => { - it('メッセージを送信できる', async(async () => { - const res = await request('/messaging/messages/create', { - userId: bob.id, - text: 'test' - }, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(typeof res.body === 'object' && !Array.isArray(res.body), true); - assert.strictEqual(res.body.text, 'test'); - })); - - it('自分自身にはメッセージを送信できない', async(async () => { - const res = await request('/messaging/messages/create', { - userId: alice.id, - text: 'Yo' - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('存在しないユーザーにはメッセージを送信できない', async(async () => { - const res = await request('/messaging/messages/create', { - userId: '000000000000000000000000', - text: 'test' - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('不正なユーザーIDで怒られる', async(async () => { - const res = await request('/messaging/messages/create', { - userId: 'foo', - text: 'test' - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('テキストが無くて怒られる', async(async () => { - const res = await request('/messaging/messages/create', { - userId: bob.id - }, alice); - - assert.strictEqual(res.status, 400); - })); - - it('文字数オーバーで怒られる', async(async () => { - const res = await request('/messaging/messages/create', { - userId: bob.id, - text: '!'.repeat(1001) - }, alice); - - assert.strictEqual(res.status, 400); - })); - }); - - describe('notes/replies', () => { - it('自分に閲覧権限のない投稿は含まれない', async(async () => { - const alicePost = await post(alice, { - text: 'foo' - }); - - await post(bob, { - replyId: alicePost.id, - text: 'bar', - visibility: 'specified', - visibleUserIds: [alice.id] - }); - - const res = await request('/notes/replies', { - noteId: alicePost.id - }, carol); - - assert.strictEqual(res.status, 200); - assert.strictEqual(Array.isArray(res.body), true); - assert.strictEqual(res.body.length, 0); - })); - }); - - describe('notes/timeline', () => { - it('フォロワー限定投稿が含まれる', async(async () => { - await request('/following/create', { - userId: alice.id - }, bob); - - const alicePost = await post(alice, { - text: 'foo', - visibility: 'followers' - }); - - const res = await request('/notes/timeline', {}, bob); - - assert.strictEqual(res.status, 200); - assert.strictEqual(Array.isArray(res.body), true); - assert.strictEqual(res.body.length, 1); - assert.strictEqual(res.body[0].id, alicePost.id); - })); - }); -}); -*/ diff --git a/packages/backend/test/extract-mentions.ts b/packages/backend/test/extract-mentions.ts deleted file mode 100644 index f400e1e634..0000000000 --- a/packages/backend/test/extract-mentions.ts +++ /dev/null @@ -1,50 +0,0 @@ -import * as assert from "assert"; - -import { parse } from "mfm-js"; -import { extractMentions } from "../src/misc/extract-mentions.js"; - -describe("Extract mentions", () => { - it("simple", () => { - const ast = parse("@foo @bar @baz")!; - const mentions = extractMentions(ast); - assert.deepStrictEqual(mentions, [ - { - username: "foo", - acct: "@foo", - host: null, - }, - { - username: "bar", - acct: "@bar", - host: null, - }, - { - username: "baz", - acct: "@baz", - host: null, - }, - ]); - }); - - it("nested", () => { - const ast = parse("@foo **@bar** @baz")!; - const mentions = extractMentions(ast); - assert.deepStrictEqual(mentions, [ - { - username: "foo", - acct: "@foo", - host: null, - }, - { - username: "bar", - acct: "@bar", - host: null, - }, - { - username: "baz", - acct: "@baz", - host: null, - }, - ]); - }); -}); diff --git a/packages/backend/test/fetch-resource.ts b/packages/backend/test/fetch-resource.ts deleted file mode 100644 index da3116f0e8..0000000000 --- a/packages/backend/test/fetch-resource.ts +++ /dev/null @@ -1,213 +0,0 @@ -process.env.NODE_ENV = "test"; - -import * as assert from "assert"; -import * as childProcess from "child_process"; -import * as openapi from "@redocly/openapi-core"; -import { - async, - startServer, - signup, - post, - request, - simpleGet, - port, - shutdownServer, -} from "./utils.js"; - -// Request Accept -const ONLY_AP = "application/activity+json"; -const PREFER_AP = "application/activity+json, */*"; -const PREFER_HTML = "text/html, */*"; -const UNSPECIFIED = "*/*"; - -// Response Contet-Type -const AP = "application/activity+json; charset=utf-8"; -const JSON = "application/json; charset=utf-8"; -const HTML = "text/html; charset=utf-8"; - -describe("Fetch resource", () => { - let p: childProcess.ChildProcess; - - let alice: any; - let alicesPost: any; - - before(async () => { - p = await startServer(); - alice = await signup({ username: "alice" }); - alicesPost = await post(alice, { - text: "test", - }); - }); - - after(async () => { - await shutdownServer(p); - }); - - describe("Common", () => { - it("meta", async(async () => { - const res = await request("/meta", {}); - - assert.strictEqual(res.status, 200); - })); - - it("GET root", async(async () => { - const res = await simpleGet("/"); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, HTML); - })); - - it("GET docs", async(async () => { - const res = await simpleGet("/docs/ja-JP/about"); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, HTML); - })); - - it("GET api-doc", async(async () => { - const res = await simpleGet("/api-doc"); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, HTML); - })); - - it("GET api.json", async(async () => { - const res = await simpleGet("/api.json"); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, JSON); - })); - - it("Validate api.json", async(async () => { - const config = await openapi.loadConfig(); - const result = await openapi.bundle({ - config, - ref: `http://localhost:${port}/api.json`, - }); - - for (const problem of result.problems) { - console.log(`${problem.message} - ${problem.location[0]?.pointer}`); - } - - assert.strictEqual(result.problems.length, 0); - })); - - it("GET favicon.ico", async(async () => { - const res = await simpleGet("/favicon.ico"); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, "image/x-icon"); - })); - - it("GET apple-touch-icon.png", async(async () => { - const res = await simpleGet("/apple-touch-icon.png"); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, "image/png"); - })); - - it("GET twemoji svg", async(async () => { - const res = await simpleGet("/twemoji/2764.svg"); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, "image/svg+xml"); - })); - - it("GET twemoji svg with hyphen", async(async () => { - const res = await simpleGet("/twemoji/2764-fe0f-200d-1f525.svg"); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, "image/svg+xml"); - })); - }); - - describe("/@:username", () => { - it("Only AP => AP", async(async () => { - const res = await simpleGet(`/@${alice.username}`, ONLY_AP); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, AP); - })); - - it("Prefer AP => AP", async(async () => { - const res = await simpleGet(`/@${alice.username}`, PREFER_AP); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, AP); - })); - - it("Prefer HTML => HTML", async(async () => { - const res = await simpleGet(`/@${alice.username}`, PREFER_HTML); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, HTML); - })); - - it("Unspecified => HTML", async(async () => { - const res = await simpleGet(`/@${alice.username}`, UNSPECIFIED); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, HTML); - })); - }); - - describe("/users/:id", () => { - it("Only AP => AP", async(async () => { - const res = await simpleGet(`/users/${alice.id}`, ONLY_AP); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, AP); - })); - - it("Prefer AP => AP", async(async () => { - const res = await simpleGet(`/users/${alice.id}`, PREFER_AP); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, AP); - })); - - it("Prefer HTML => Redirect to /@:username", async(async () => { - const res = await simpleGet(`/users/${alice.id}`, PREFER_HTML); - assert.strictEqual(res.status, 302); - assert.strictEqual(res.location, `/@${alice.username}`); - })); - - it("Undecided => HTML", async(async () => { - const res = await simpleGet(`/users/${alice.id}`, UNSPECIFIED); - assert.strictEqual(res.status, 302); - assert.strictEqual(res.location, `/@${alice.username}`); - })); - }); - - describe("/notes/:id", () => { - it("Only AP => AP", async(async () => { - const res = await simpleGet(`/notes/${alicesPost.id}`, ONLY_AP); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, AP); - })); - - it("Prefer AP => AP", async(async () => { - const res = await simpleGet(`/notes/${alicesPost.id}`, PREFER_AP); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, AP); - })); - - it("Prefer HTML => HTML", async(async () => { - const res = await simpleGet(`/notes/${alicesPost.id}`, PREFER_HTML); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, HTML); - })); - - it("Unspecified => HTML", async(async () => { - const res = await simpleGet(`/notes/${alicesPost.id}`, UNSPECIFIED); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, HTML); - })); - }); - - describe("Feeds", () => { - it("RSS", async(async () => { - const res = await simpleGet(`/@${alice.username}.rss`, UNSPECIFIED); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, "application/rss+xml; charset=utf-8"); - })); - - it("ATOM", async(async () => { - const res = await simpleGet(`/@${alice.username}.atom`, UNSPECIFIED); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, "application/atom+xml; charset=utf-8"); - })); - - it("JSON", async(async () => { - const res = await simpleGet(`/@${alice.username}.json`, UNSPECIFIED); - assert.strictEqual(res.status, 200); - assert.strictEqual(res.type, "application/json; charset=utf-8"); - })); - }); -}); diff --git a/packages/backend/test/ff-visibility.ts b/packages/backend/test/ff-visibility.ts deleted file mode 100644 index f898926d99..0000000000 --- a/packages/backend/test/ff-visibility.ts +++ /dev/null @@ -1,283 +0,0 @@ -process.env.NODE_ENV = "test"; - -import * as assert from "assert"; -import * as childProcess from "child_process"; -import { - async, - signup, - request, - post, - react, - connectStream, - startServer, - shutdownServer, - simpleGet, -} from "./utils.js"; - -describe("FF visibility", () => { - let p: childProcess.ChildProcess; - - let alice: any; - let bob: any; - let carol: any; - - before(async () => { - p = await startServer(); - alice = await signup({ username: "alice" }); - bob = await signup({ username: "bob" }); - carol = await signup({ username: "carol" }); - }); - - after(async () => { - await shutdownServer(p); - }); - - it("ffVisibility が public なユーザーのフォロー/フォロワーを誰でも見れる", async(async () => { - await request( - "/i/update", - { - ffVisibility: "public", - }, - alice, - ); - - const followingRes = await request( - "/users/following", - { - userId: alice.id, - }, - bob, - ); - const followersRes = await request( - "/users/followers", - { - userId: alice.id, - }, - bob, - ); - - assert.strictEqual(followingRes.status, 200); - assert.strictEqual(Array.isArray(followingRes.body), true); - assert.strictEqual(followersRes.status, 200); - assert.strictEqual(Array.isArray(followersRes.body), true); - })); - - it("ffVisibility が followers なユーザーのフォロー/フォロワーを自分で見れる", async(async () => { - await request( - "/i/update", - { - ffVisibility: "followers", - }, - alice, - ); - - const followingRes = await request( - "/users/following", - { - userId: alice.id, - }, - alice, - ); - const followersRes = await request( - "/users/followers", - { - userId: alice.id, - }, - alice, - ); - - assert.strictEqual(followingRes.status, 200); - assert.strictEqual(Array.isArray(followingRes.body), true); - assert.strictEqual(followersRes.status, 200); - assert.strictEqual(Array.isArray(followersRes.body), true); - })); - - it("ffVisibility が followers なユーザーのフォロー/フォロワーを非フォロワーが見れない", async(async () => { - await request( - "/i/update", - { - ffVisibility: "followers", - }, - alice, - ); - - const followingRes = await request( - "/users/following", - { - userId: alice.id, - }, - bob, - ); - const followersRes = await request( - "/users/followers", - { - userId: alice.id, - }, - bob, - ); - - assert.strictEqual(followingRes.status, 400); - assert.strictEqual(followersRes.status, 400); - })); - - it("ffVisibility が followers なユーザーのフォロー/フォロワーをフォロワーが見れる", async(async () => { - await request( - "/i/update", - { - ffVisibility: "followers", - }, - alice, - ); - - await request( - "/following/create", - { - userId: alice.id, - }, - bob, - ); - - const followingRes = await request( - "/users/following", - { - userId: alice.id, - }, - bob, - ); - const followersRes = await request( - "/users/followers", - { - userId: alice.id, - }, - bob, - ); - - assert.strictEqual(followingRes.status, 200); - assert.strictEqual(Array.isArray(followingRes.body), true); - assert.strictEqual(followersRes.status, 200); - assert.strictEqual(Array.isArray(followersRes.body), true); - })); - - it("ffVisibility が private なユーザーのフォロー/フォロワーを自分で見れる", async(async () => { - await request( - "/i/update", - { - ffVisibility: "private", - }, - alice, - ); - - const followingRes = await request( - "/users/following", - { - userId: alice.id, - }, - alice, - ); - const followersRes = await request( - "/users/followers", - { - userId: alice.id, - }, - alice, - ); - - assert.strictEqual(followingRes.status, 200); - assert.strictEqual(Array.isArray(followingRes.body), true); - assert.strictEqual(followersRes.status, 200); - assert.strictEqual(Array.isArray(followersRes.body), true); - })); - - it("ffVisibility が private なユーザーのフォロー/フォロワーを他人が見れない", async(async () => { - await request( - "/i/update", - { - ffVisibility: "private", - }, - alice, - ); - - const followingRes = await request( - "/users/following", - { - userId: alice.id, - }, - bob, - ); - const followersRes = await request( - "/users/followers", - { - userId: alice.id, - }, - bob, - ); - - assert.strictEqual(followingRes.status, 400); - assert.strictEqual(followersRes.status, 400); - })); - - describe("AP", () => { - it("ffVisibility が public 以外ならばAPからは取得できない", async(async () => { - { - await request( - "/i/update", - { - ffVisibility: "public", - }, - alice, - ); - - const followingRes = await simpleGet( - `/users/${alice.id}/following`, - "application/activity+json", - ); - const followersRes = await simpleGet( - `/users/${alice.id}/followers`, - "application/activity+json", - ); - assert.strictEqual(followingRes.status, 200); - assert.strictEqual(followersRes.status, 200); - } - { - await request( - "/i/update", - { - ffVisibility: "followers", - }, - alice, - ); - - const followingRes = await simpleGet( - `/users/${alice.id}/following`, - "application/activity+json", - ).catch((res) => ({ status: res.statusCode })); - const followersRes = await simpleGet( - `/users/${alice.id}/followers`, - "application/activity+json", - ).catch((res) => ({ status: res.statusCode })); - assert.strictEqual(followingRes.status, 403); - assert.strictEqual(followersRes.status, 403); - } - { - await request( - "/i/update", - { - ffVisibility: "private", - }, - alice, - ); - - const followingRes = await simpleGet( - `/users/${alice.id}/following`, - "application/activity+json", - ).catch((res) => ({ status: res.statusCode })); - const followersRes = await simpleGet( - `/users/${alice.id}/followers`, - "application/activity+json", - ).catch((res) => ({ status: res.statusCode })); - assert.strictEqual(followingRes.status, 403); - assert.strictEqual(followersRes.status, 403); - } - })); - }); -}); diff --git a/packages/backend/test/get-file-info.ts b/packages/backend/test/get-file-info.ts deleted file mode 100644 index 22dc28c8e0..0000000000 --- a/packages/backend/test/get-file-info.ts +++ /dev/null @@ -1,209 +0,0 @@ -import * as assert from "assert"; -import { fileURLToPath } from "node:url"; -import { dirname } from "node:path"; -import { getFileInfo } from "../src/misc/get-file-info.js"; -import { async } from "./utils.js"; - -const _filename = fileURLToPath(import.meta.url); -const _dirname = dirname(_filename); - -describe("Get file info", () => { - it("Empty file", async(async () => { - const path = `${_dirname}/resources/emptyfile`; - const info = (await getFileInfo(path, { - skipSensitiveDetection: true, - })) as any; - delete info.warnings; - delete info.blurhash; - delete info.sensitive; - delete info.porn; - assert.deepStrictEqual(info, { - size: 0, - md5: "d41d8cd98f00b204e9800998ecf8427e", - type: { - mime: "application/octet-stream", - ext: null, - }, - width: undefined, - height: undefined, - orientation: undefined, - }); - })); - - it("Generic JPEG", async(async () => { - const path = `${_dirname}/resources/Lenna.jpg`; - const info = (await getFileInfo(path, { - skipSensitiveDetection: true, - })) as any; - delete info.warnings; - delete info.blurhash; - delete info.sensitive; - delete info.porn; - assert.deepStrictEqual(info, { - size: 25360, - md5: "091b3f259662aa31e2ffef4519951168", - type: { - mime: "image/jpeg", - ext: "jpg", - }, - width: 512, - height: 512, - orientation: undefined, - }); - })); - - it("Generic APNG", async(async () => { - const path = `${_dirname}/resources/anime.png`; - const info = (await getFileInfo(path, { - skipSensitiveDetection: true, - })) as any; - delete info.warnings; - delete info.blurhash; - delete info.sensitive; - delete info.porn; - assert.deepStrictEqual(info, { - size: 1868, - md5: "08189c607bea3b952704676bb3c979e0", - type: { - mime: "image/apng", - ext: "apng", - }, - width: 256, - height: 256, - orientation: undefined, - }); - })); - - it("Generic AGIF", async(async () => { - const path = `${_dirname}/resources/anime.gif`; - const info = (await getFileInfo(path, { - skipSensitiveDetection: true, - })) as any; - delete info.warnings; - delete info.blurhash; - delete info.sensitive; - delete info.porn; - assert.deepStrictEqual(info, { - size: 2248, - md5: "32c47a11555675d9267aee1a86571e7e", - type: { - mime: "image/gif", - ext: "gif", - }, - width: 256, - height: 256, - orientation: undefined, - }); - })); - - it("PNG with alpha", async(async () => { - const path = `${_dirname}/resources/with-alpha.png`; - const info = (await getFileInfo(path, { - skipSensitiveDetection: true, - })) as any; - delete info.warnings; - delete info.blurhash; - delete info.sensitive; - delete info.porn; - assert.deepStrictEqual(info, { - size: 3772, - md5: "f73535c3e1e27508885b69b10cf6e991", - type: { - mime: "image/png", - ext: "png", - }, - width: 256, - height: 256, - orientation: undefined, - }); - })); - - it("Generic SVG", async(async () => { - const path = `${_dirname}/resources/image.svg`; - const info = (await getFileInfo(path, { - skipSensitiveDetection: true, - })) as any; - delete info.warnings; - delete info.blurhash; - delete info.sensitive; - delete info.porn; - assert.deepStrictEqual(info, { - size: 505, - md5: "b6f52b4b021e7b92cdd04509c7267965", - type: { - mime: "image/svg+xml", - ext: "svg", - }, - width: 256, - height: 256, - orientation: undefined, - }); - })); - - it("SVG with XML definition", async(async () => { - // https://github.com/misskey-dev/misskey/issues/4413 - const path = `${_dirname}/resources/with-xml-def.svg`; - const info = (await getFileInfo(path, { - skipSensitiveDetection: true, - })) as any; - delete info.warnings; - delete info.blurhash; - delete info.sensitive; - delete info.porn; - assert.deepStrictEqual(info, { - size: 544, - md5: "4b7a346cde9ccbeb267e812567e33397", - type: { - mime: "image/svg+xml", - ext: "svg", - }, - width: 256, - height: 256, - orientation: undefined, - }); - })); - - it("Dimension limit", async(async () => { - const path = `${_dirname}/resources/25000x25000.png`; - const info = (await getFileInfo(path, { - skipSensitiveDetection: true, - })) as any; - delete info.warnings; - delete info.blurhash; - delete info.sensitive; - delete info.porn; - assert.deepStrictEqual(info, { - size: 75933, - md5: "268c5dde99e17cf8fe09f1ab3f97df56", - type: { - mime: "application/octet-stream", // do not treat as image - ext: null, - }, - width: 25000, - height: 25000, - orientation: undefined, - }); - })); - - it("Rotate JPEG", async(async () => { - const path = `${_dirname}/resources/rotate.jpg`; - const info = (await getFileInfo(path, { - skipSensitiveDetection: true, - })) as any; - delete info.warnings; - delete info.blurhash; - delete info.sensitive; - delete info.porn; - assert.deepStrictEqual(info, { - size: 12624, - md5: "68d5b2d8d1d1acbbce99203e3ec3857e", - type: { - mime: "image/jpeg", - ext: "jpg", - }, - width: 512, - height: 256, - orientation: 8, - }); - })); -}); diff --git a/packages/backend/test/loader.js b/packages/backend/test/loader.js deleted file mode 100644 index 7e1bf379dc..0000000000 --- a/packages/backend/test/loader.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * ts-node/esmローダーに投げる前にpath mappingを解決する - * 参考 - * - https://github.com/TypeStrong/ts-node/discussions/1450#discussioncomment-1806115 - * - https://nodejs.org/api/esm.html#loaders - * ※ https://github.com/TypeStrong/ts-node/pull/1585 が取り込まれたらこのカスタムローダーは必要なくなる - */ - -import { resolve as resolveTs, load } from "ts-node/esm"; -import { loadConfig, createMatchPath } from "tsconfig-paths"; -import { pathToFileURL } from "url"; - -const tsconfig = loadConfig(); -const matchPath = createMatchPath(tsconfig.absoluteBaseUrl, tsconfig.paths); - -export function resolve(specifier, ctx, defaultResolve) { - let resolvedSpecifier; - if (specifier.endsWith(".js")) { - // maybe transpiled - const specifierWithoutExtension = specifier.substring( - 0, - specifier.length - ".js".length, - ); - const matchedSpecifier = matchPath(specifierWithoutExtension); - if (matchedSpecifier) { - resolvedSpecifier = pathToFileURL(`${matchedSpecifier}.js`).href; - } - } else { - const matchedSpecifier = matchPath(specifier); - if (matchedSpecifier) { - resolvedSpecifier = pathToFileURL(matchedSpecifier).href; - } - } - return resolveTs(resolvedSpecifier ?? specifier, ctx, defaultResolve); -} - -export { load }; diff --git a/packages/backend/test/mfm.ts b/packages/backend/test/mfm.ts deleted file mode 100644 index 605daa7107..0000000000 --- a/packages/backend/test/mfm.ts +++ /dev/null @@ -1,127 +0,0 @@ -import * as assert from "assert"; -import * as mfm from "mfm-js"; - -import { toHtml } from "../src/mfm/to-html.js"; -import { fromHtml } from "../src/mfm/from-html.js"; - -describe("toHtml", () => { - it("br", () => { - const input = "foo\nbar\nbaz"; - const output = "<p><span>foo<br>bar<br>baz</span></p>"; - assert.equal(toHtml(mfm.parse(input)), output); - }); - - it("br alt", () => { - const input = "foo\r\nbar\rbaz"; - const output = "<p><span>foo<br>bar<br>baz</span></p>"; - assert.equal(toHtml(mfm.parse(input)), output); - }); -}); - -describe("fromHtml", () => { - it("p", () => { - assert.deepStrictEqual(fromHtml("<p>a</p><p>b</p>"), "a\n\nb"); - }); - - it("block element", () => { - assert.deepStrictEqual(fromHtml("<div>a</div><div>b</div>"), "a\nb"); - }); - - it("inline element", () => { - assert.deepStrictEqual(fromHtml("<ul><li>a</li><li>b</li></ul>"), "a\nb"); - }); - - it("block code", () => { - assert.deepStrictEqual( - fromHtml("<pre><code>a\nb</code></pre>"), - "```\na\nb\n```", - ); - }); - - it("inline code", () => { - assert.deepStrictEqual(fromHtml("<code>a</code>"), "`a`"); - }); - - it("quote", () => { - assert.deepStrictEqual( - fromHtml("<blockquote>a\nb</blockquote>"), - "> a\n> b", - ); - }); - - it("br", () => { - assert.deepStrictEqual(fromHtml("<p>abc<br><br/>d</p>"), "abc\n\nd"); - }); - - it("link with different text", () => { - assert.deepStrictEqual( - fromHtml('<p>a <a href="https://example.com/b">c</a> d</p>'), - "a [c](https://example.com/b) d", - ); - }); - - it("link with different text, but not encoded", () => { - assert.deepStrictEqual( - fromHtml('<p>a <a href="https://example.com/ä">c</a> d</p>'), - "a [c](<https://example.com/ä>) d", - ); - }); - - it("link with same text", () => { - assert.deepStrictEqual( - fromHtml( - '<p>a <a href="https://example.com/b">https://example.com/b</a> d</p>', - ), - "a https://example.com/b d", - ); - }); - - it("link with same text, but not encoded", () => { - assert.deepStrictEqual( - fromHtml( - '<p>a <a href="https://example.com/ä">https://example.com/ä</a> d</p>', - ), - "a <https://example.com/ä> d", - ); - }); - - it("link with no url", () => { - assert.deepStrictEqual( - fromHtml('<p>a <a href="b">c</a> d</p>'), - "a [c](b) d", - ); - }); - - it("link without href", () => { - assert.deepStrictEqual(fromHtml("<p>a <a>c</a> d</p>"), "a c d"); - }); - - it("link without text", () => { - assert.deepStrictEqual( - fromHtml('<p>a <a href="https://example.com/b"></a> d</p>'), - "a https://example.com/b d", - ); - }); - - it("link without both", () => { - assert.deepStrictEqual(fromHtml("<p>a <a></a> d</p>"), "a d"); - }); - - it("mention", () => { - assert.deepStrictEqual( - fromHtml( - '<p>a <a href="https://example.com/@user" class="u-url mention">@user</a> d</p>', - ), - "a @user@example.com d", - ); - }); - - it("hashtag", () => { - assert.deepStrictEqual( - fromHtml('<p>a <a href="https://example.com/tags/a">#a</a> d</p>', [ - "#a", - ]), - "a #a d", - ); - }); -}); diff --git a/packages/backend/test/misc/mock-resolver.ts b/packages/backend/test/misc/mock-resolver.ts deleted file mode 100644 index 74c67e3d3f..0000000000 --- a/packages/backend/test/misc/mock-resolver.ts +++ /dev/null @@ -1,39 +0,0 @@ -import Resolver from "../../src/remote/activitypub/resolver.js"; -import { IObject } from "../../src/remote/activitypub/type.js"; - -type MockResponse = { - type: string; - content: string; -}; - -export class MockResolver extends Resolver { - private _rs = new Map<string, MockResponse>(); - public async _register( - uri: string, - content: string | Record<string, any>, - type = "application/activity+json", - ) { - this._rs.set(uri, { - type, - content: typeof content === "string" ? content : JSON.stringify(content), - }); - } - - public async resolve(value: string | IObject): Promise<IObject> { - if (typeof value !== "string") return value; - - const r = this._rs.get(value); - - if (!r) { - throw { - name: "StatusError", - statusCode: 404, - message: "Not registed for mock", - }; - } - - const object = JSON.parse(r.content); - - return object; - } -} diff --git a/packages/backend/test/mute.ts b/packages/backend/test/mute.ts deleted file mode 100644 index c511628342..0000000000 --- a/packages/backend/test/mute.ts +++ /dev/null @@ -1,176 +0,0 @@ -process.env.NODE_ENV = "test"; - -import * as assert from "assert"; -import * as childProcess from "child_process"; -import { - async, - signup, - request, - post, - react, - startServer, - shutdownServer, - waitFire, -} from "./utils.js"; - -describe("Mute", () => { - let p: childProcess.ChildProcess; - - // alice mutes carol - let alice: any; - let bob: any; - let carol: any; - - before(async () => { - p = await startServer(); - alice = await signup({ username: "alice" }); - bob = await signup({ username: "bob" }); - carol = await signup({ username: "carol" }); - }); - - after(async () => { - await shutdownServer(p); - }); - - it("ミュート作成", async(async () => { - const res = await request( - "/mute/create", - { - userId: carol.id, - }, - alice, - ); - - assert.strictEqual(res.status, 204); - })); - - it("「自分宛ての投稿」にミュートしているユーザーの投稿が含まれない", async(async () => { - const bobNote = await post(bob, { text: "@alice hi" }); - const carolNote = await post(carol, { text: "@alice hi" }); - - const res = await request("/notes/mentions", {}, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(Array.isArray(res.body), true); - assert.strictEqual( - res.body.some((note: any) => note.id === bobNote.id), - true, - ); - assert.strictEqual( - res.body.some((note: any) => note.id === carolNote.id), - false, - ); - })); - - it("ミュートしているユーザーからメンションされても、hasUnreadMentions が true にならない", async(async () => { - // 状態リセット - await request("/i/read-all-unread-notes", {}, alice); - - await post(carol, { text: "@alice hi" }); - - const res = await request("/i", {}, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(res.body.hasUnreadMentions, false); - })); - - it("ミュートしているユーザーからメンションされても、ストリームに unreadMention イベントが流れてこない", async () => { - // 状態リセット - await request("/i/read-all-unread-notes", {}, alice); - - const fired = await waitFire( - alice, - "main", - () => post(carol, { text: "@alice hi" }), - (msg) => msg.type === "unreadMention", - ); - - assert.strictEqual(fired, false); - }); - - it("ミュートしているユーザーからメンションされても、ストリームに unreadNotification イベントが流れてこない", async () => { - // 状態リセット - await request("/i/read-all-unread-notes", {}, alice); - await request("/notifications/mark-all-as-read", {}, alice); - - const fired = await waitFire( - alice, - "main", - () => post(carol, { text: "@alice hi" }), - (msg) => msg.type === "unreadNotification", - ); - - assert.strictEqual(fired, false); - }); - - describe("Timeline", () => { - it("タイムラインにミュートしているユーザーの投稿が含まれない", async(async () => { - const aliceNote = await post(alice); - const bobNote = await post(bob); - const carolNote = await post(carol); - - const res = await request("/notes/local-timeline", {}, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(Array.isArray(res.body), true); - assert.strictEqual( - res.body.some((note: any) => note.id === aliceNote.id), - true, - ); - assert.strictEqual( - res.body.some((note: any) => note.id === bobNote.id), - true, - ); - assert.strictEqual( - res.body.some((note: any) => note.id === carolNote.id), - false, - ); - })); - - it("タイムラインにミュートしているユーザーの投稿のRenoteが含まれない", async(async () => { - const aliceNote = await post(alice); - const carolNote = await post(carol); - const bobNote = await post(bob, { - renoteId: carolNote.id, - }); - - const res = await request("/notes/local-timeline", {}, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(Array.isArray(res.body), true); - assert.strictEqual( - res.body.some((note: any) => note.id === aliceNote.id), - true, - ); - assert.strictEqual( - res.body.some((note: any) => note.id === bobNote.id), - false, - ); - assert.strictEqual( - res.body.some((note: any) => note.id === carolNote.id), - false, - ); - })); - }); - - describe("Notification", () => { - it("通知にミュートしているユーザーの通知が含まれない(リアクション)", async(async () => { - const aliceNote = await post(alice); - await react(bob, aliceNote, "like"); - await react(carol, aliceNote, "like"); - - const res = await request("/i/notifications", {}, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(Array.isArray(res.body), true); - assert.strictEqual( - res.body.some((notification: any) => notification.userId === bob.id), - true, - ); - assert.strictEqual( - res.body.some((notification: any) => notification.userId === carol.id), - false, - ); - })); - }); -}); diff --git a/packages/backend/test/note.ts b/packages/backend/test/note.ts deleted file mode 100644 index 3af4b88d87..0000000000 --- a/packages/backend/test/note.ts +++ /dev/null @@ -1,517 +0,0 @@ -process.env.NODE_ENV = "test"; - -import * as assert from "assert"; -import * as childProcess from "child_process"; -import { Note } from "../src/models/entities/note.js"; -import { - async, - signup, - request, - post, - uploadUrl, - startServer, - shutdownServer, - initTestDb, - api, -} from "./utils.js"; - -describe("Note", () => { - let p: childProcess.ChildProcess; - let Notes: any; - - let alice: any; - let bob: any; - - before(async () => { - p = await startServer(); - const connection = await initTestDb(true); - Notes = connection.getRepository(Note); - alice = await signup({ username: "alice" }); - bob = await signup({ username: "bob" }); - }); - - after(async () => { - await shutdownServer(p); - }); - - it("投稿できる", async(async () => { - const post = { - text: "test", - }; - - const res = await request("/notes/create", post, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual( - typeof res.body === "object" && !Array.isArray(res.body), - true, - ); - assert.strictEqual(res.body.createdNote.text, post.text); - })); - - it("ファイルを添付できる", async(async () => { - const file = await uploadUrl( - alice, - "https://raw.githubusercontent.com/misskey-dev/misskey/develop/packages/backend/test/resources/Lenna.jpg", - ); - - const res = await request( - "/notes/create", - { - fileIds: [file.id], - }, - alice, - ); - - assert.strictEqual(res.status, 200); - assert.strictEqual( - typeof res.body === "object" && !Array.isArray(res.body), - true, - ); - assert.deepStrictEqual(res.body.createdNote.fileIds, [file.id]); - })); - - it("他人のファイルは無視", async(async () => { - const file = await uploadUrl( - bob, - "https://raw.githubusercontent.com/misskey-dev/misskey/develop/packages/backend/test/resources/Lenna.jpg", - ); - - const res = await request( - "/notes/create", - { - text: "test", - fileIds: [file.id], - }, - alice, - ); - - assert.strictEqual(res.status, 200); - assert.strictEqual( - typeof res.body === "object" && !Array.isArray(res.body), - true, - ); - assert.deepStrictEqual(res.body.createdNote.fileIds, []); - })); - - it("存在しないファイルは無視", async(async () => { - const res = await request( - "/notes/create", - { - text: "test", - fileIds: ["000000000000000000000000"], - }, - alice, - ); - - assert.strictEqual(res.status, 200); - assert.strictEqual( - typeof res.body === "object" && !Array.isArray(res.body), - true, - ); - assert.deepStrictEqual(res.body.createdNote.fileIds, []); - })); - - it("不正なファイルIDは無視", async(async () => { - const res = await request( - "/notes/create", - { - fileIds: ["kyoppie"], - }, - alice, - ); - assert.strictEqual(res.status, 200); - assert.strictEqual( - typeof res.body === "object" && !Array.isArray(res.body), - true, - ); - assert.deepStrictEqual(res.body.createdNote.fileIds, []); - })); - - it("返信できる", async(async () => { - const bobPost = await post(bob, { - text: "foo", - }); - - const alicePost = { - text: "bar", - replyId: bobPost.id, - }; - - const res = await request("/notes/create", alicePost, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual( - typeof res.body === "object" && !Array.isArray(res.body), - true, - ); - assert.strictEqual(res.body.createdNote.text, alicePost.text); - assert.strictEqual(res.body.createdNote.replyId, alicePost.replyId); - assert.strictEqual(res.body.createdNote.reply.text, bobPost.text); - })); - - it("renoteできる", async(async () => { - const bobPost = await post(bob, { - text: "test", - }); - - const alicePost = { - renoteId: bobPost.id, - }; - - const res = await request("/notes/create", alicePost, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual( - typeof res.body === "object" && !Array.isArray(res.body), - true, - ); - assert.strictEqual(res.body.createdNote.renoteId, alicePost.renoteId); - assert.strictEqual(res.body.createdNote.renote.text, bobPost.text); - })); - - it("引用renoteできる", async(async () => { - const bobPost = await post(bob, { - text: "test", - }); - - const alicePost = { - text: "test", - renoteId: bobPost.id, - }; - - const res = await request("/notes/create", alicePost, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual( - typeof res.body === "object" && !Array.isArray(res.body), - true, - ); - assert.strictEqual(res.body.createdNote.text, alicePost.text); - assert.strictEqual(res.body.createdNote.renoteId, alicePost.renoteId); - assert.strictEqual(res.body.createdNote.renote.text, bobPost.text); - })); - - it("文字数ぎりぎりで怒られない", async(async () => { - const post = { - text: "!".repeat(3000), - }; - const res = await request("/notes/create", post, alice); - assert.strictEqual(res.status, 200); - })); - - it("文字数オーバーで怒られる", async(async () => { - const post = { - text: "!".repeat(3001), - }; - const res = await request("/notes/create", post, alice); - assert.strictEqual(res.status, 400); - })); - - it("存在しないリプライ先で怒られる", async(async () => { - const post = { - text: "test", - replyId: "000000000000000000000000", - }; - const res = await request("/notes/create", post, alice); - assert.strictEqual(res.status, 400); - })); - - it("存在しないrenote対象で怒られる", async(async () => { - const post = { - renoteId: "000000000000000000000000", - }; - const res = await request("/notes/create", post, alice); - assert.strictEqual(res.status, 400); - })); - - it("不正なリプライ先IDで怒られる", async(async () => { - const post = { - text: "test", - replyId: "foo", - }; - const res = await request("/notes/create", post, alice); - assert.strictEqual(res.status, 400); - })); - - it("不正なrenote対象IDで怒られる", async(async () => { - const post = { - renoteId: "foo", - }; - const res = await request("/notes/create", post, alice); - assert.strictEqual(res.status, 400); - })); - - it("存在しないユーザーにメンションできる", async(async () => { - const post = { - text: "@ghost yo", - }; - - const res = await request("/notes/create", post, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual( - typeof res.body === "object" && !Array.isArray(res.body), - true, - ); - assert.strictEqual(res.body.createdNote.text, post.text); - })); - - it("同じユーザーに複数メンションしても内部的にまとめられる", async(async () => { - const post = { - text: "@bob @bob @bob yo", - }; - - const res = await request("/notes/create", post, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual( - typeof res.body === "object" && !Array.isArray(res.body), - true, - ); - assert.strictEqual(res.body.createdNote.text, post.text); - - const noteDoc = await Notes.findOneBy({ id: res.body.createdNote.id }); - assert.deepStrictEqual(noteDoc.mentions, [bob.id]); - })); - - describe("notes/create", () => { - it("投票を添付できる", async(async () => { - const res = await request( - "/notes/create", - { - text: "test", - poll: { - choices: ["foo", "bar"], - }, - }, - alice, - ); - - assert.strictEqual(res.status, 200); - assert.strictEqual( - typeof res.body === "object" && !Array.isArray(res.body), - true, - ); - assert.strictEqual(res.body.createdNote.poll != null, true); - })); - - it("投票の選択肢が無くて怒られる", async(async () => { - const res = await request( - "/notes/create", - { - poll: {}, - }, - alice, - ); - assert.strictEqual(res.status, 400); - })); - - it("投票の選択肢が無くて怒られる (空の配列)", async(async () => { - const res = await request( - "/notes/create", - { - poll: { - choices: [], - }, - }, - alice, - ); - assert.strictEqual(res.status, 400); - })); - - it("投票の選択肢が1つで怒られる", async(async () => { - const res = await request( - "/notes/create", - { - poll: { - choices: ["Strawberry Pasta"], - }, - }, - alice, - ); - assert.strictEqual(res.status, 400); - })); - - it("投票できる", async(async () => { - const { body } = await request( - "/notes/create", - { - text: "test", - poll: { - choices: ["sakura", "izumi", "ako"], - }, - }, - alice, - ); - - const res = await request( - "/notes/polls/vote", - { - noteId: body.createdNote.id, - choice: 1, - }, - alice, - ); - - assert.strictEqual(res.status, 204); - })); - - it("複数投票できない", async(async () => { - const { body } = await request( - "/notes/create", - { - text: "test", - poll: { - choices: ["sakura", "izumi", "ako"], - }, - }, - alice, - ); - - await request( - "/notes/polls/vote", - { - noteId: body.createdNote.id, - choice: 0, - }, - alice, - ); - - const res = await request( - "/notes/polls/vote", - { - noteId: body.createdNote.id, - choice: 2, - }, - alice, - ); - - assert.strictEqual(res.status, 400); - })); - - it("許可されている場合は複数投票できる", async(async () => { - const { body } = await request( - "/notes/create", - { - text: "test", - poll: { - choices: ["sakura", "izumi", "ako"], - multiple: true, - }, - }, - alice, - ); - - await request( - "/notes/polls/vote", - { - noteId: body.createdNote.id, - choice: 0, - }, - alice, - ); - - await request( - "/notes/polls/vote", - { - noteId: body.createdNote.id, - choice: 1, - }, - alice, - ); - - const res = await request( - "/notes/polls/vote", - { - noteId: body.createdNote.id, - choice: 2, - }, - alice, - ); - - assert.strictEqual(res.status, 204); - })); - - it("締め切られている場合は投票できない", async(async () => { - const { body } = await request( - "/notes/create", - { - text: "test", - poll: { - choices: ["sakura", "izumi", "ako"], - expiredAfter: 1, - }, - }, - alice, - ); - - await new Promise((x) => setTimeout(x, 2)); - - const res = await request( - "/notes/polls/vote", - { - noteId: body.createdNote.id, - choice: 1, - }, - alice, - ); - - assert.strictEqual(res.status, 400); - })); - }); - - describe("notes/delete", () => { - it("delete a reply", async(async () => { - const mainNoteRes = await api( - "notes/create", - { - text: "main post", - }, - alice, - ); - const replyOneRes = await api( - "notes/create", - { - text: "reply one", - replyId: mainNoteRes.body.createdNote.id, - }, - alice, - ); - const replyTwoRes = await api( - "notes/create", - { - text: "reply two", - replyId: mainNoteRes.body.createdNote.id, - }, - alice, - ); - - const deleteOneRes = await api( - "notes/delete", - { - noteId: replyOneRes.body.createdNote.id, - }, - alice, - ); - - assert.strictEqual(deleteOneRes.status, 204); - let mainNote = await Notes.findOneBy({ - id: mainNoteRes.body.createdNote.id, - }); - assert.strictEqual(mainNote.repliesCount, 1); - - const deleteTwoRes = await api( - "notes/delete", - { - noteId: replyTwoRes.body.createdNote.id, - }, - alice, - ); - - assert.strictEqual(deleteTwoRes.status, 204); - mainNote = await Notes.findOneBy({ id: mainNoteRes.body.createdNote.id }); - assert.strictEqual(mainNote.repliesCount, 0); - })); - }); -}); diff --git a/packages/backend/test/prelude/maybe.ts b/packages/backend/test/prelude/maybe.ts deleted file mode 100644 index df589981c3..0000000000 --- a/packages/backend/test/prelude/maybe.ts +++ /dev/null @@ -1,18 +0,0 @@ -import * as assert from "assert"; -import { just, nothing } from "../../src/prelude/maybe.js"; - -describe("just", () => { - it("has a value", () => { - assert.deepStrictEqual(just(3).isJust(), true); - }); - - it("has the inverse called get", () => { - assert.deepStrictEqual(just(3).get(), 3); - }); -}); - -describe("nothing", () => { - it("has no value", () => { - assert.deepStrictEqual(nothing().isJust(), false); - }); -}); diff --git a/packages/backend/test/prelude/url.ts b/packages/backend/test/prelude/url.ts deleted file mode 100644 index 5d08ff8924..0000000000 --- a/packages/backend/test/prelude/url.ts +++ /dev/null @@ -1,13 +0,0 @@ -import * as assert from "assert"; -import { query } from "../../src/prelude/url.js"; - -describe("url", () => { - it("query", () => { - const s = query({ - foo: "ふぅ", - bar: "b a r", - baz: undefined, - }); - assert.deepStrictEqual(s, "foo=%E3%81%B5%E3%81%85&bar=b%20a%20r"); - }); -}); diff --git a/packages/backend/test/reaction-lib.ts b/packages/backend/test/reaction-lib.ts deleted file mode 100644 index 7c61dc76c2..0000000000 --- a/packages/backend/test/reaction-lib.ts +++ /dev/null @@ -1,83 +0,0 @@ -/* -import * as assert from 'assert'; - -import { toDbReaction } from '../src/misc/reaction-lib.js'; - -describe('toDbReaction', async () => { - it('既存の文字列リアクションはそのまま', async () => { - assert.strictEqual(await toDbReaction('like'), 'like'); - }); - - it('Unicodeプリンは寿司化不能とするため文字列化しない', async () => { - assert.strictEqual(await toDbReaction('🍮'), '🍮'); - }); - - it('プリン以外の既存のリアクションは文字列化する like', async () => { - assert.strictEqual(await toDbReaction('👍'), 'like'); - }); - - it('プリン以外の既存のリアクションは文字列化する love', async () => { - assert.strictEqual(await toDbReaction('❤️'), 'love'); - }); - - it('プリン以外の既存のリアクションは文字列化する love 異体字セレクタなし', async () => { - assert.strictEqual(await toDbReaction('❤'), 'love'); - }); - - it('プリン以外の既存のリアクションは文字列化する laugh', async () => { - assert.strictEqual(await toDbReaction('😆'), 'laugh'); - }); - - it('プリン以外の既存のリアクションは文字列化する hmm', async () => { - assert.strictEqual(await toDbReaction('🤔'), 'hmm'); - }); - - it('プリン以外の既存のリアクションは文字列化する surprise', async () => { - assert.strictEqual(await toDbReaction('😮'), 'surprise'); - }); - - it('プリン以外の既存のリアクションは文字列化する congrats', async () => { - assert.strictEqual(await toDbReaction('🎉'), 'congrats'); - }); - - it('プリン以外の既存のリアクションは文字列化する angry', async () => { - assert.strictEqual(await toDbReaction('💢'), 'angry'); - }); - - it('プリン以外の既存のリアクションは文字列化する confused', async () => { - assert.strictEqual(await toDbReaction('😥'), 'confused'); - }); - - it('プリン以外の既存のリアクションは文字列化する rip', async () => { - assert.strictEqual(await toDbReaction('😇'), 'rip'); - }); - - it('それ以外はUnicodeのまま', async () => { - assert.strictEqual(await toDbReaction('🍅'), '🍅'); - }); - - it('異体字セレクタ除去', async () => { - assert.strictEqual(await toDbReaction('㊗️'), '㊗'); - }); - - it('異体字セレクタ除去 必要なし', async () => { - assert.strictEqual(await toDbReaction('㊗'), '㊗'); - }); - - it('fallback - undefined', async () => { - assert.strictEqual(await toDbReaction(undefined), 'like'); - }); - - it('fallback - null', async () => { - assert.strictEqual(await toDbReaction(null), 'like'); - }); - - it('fallback - empty', async () => { - assert.strictEqual(await toDbReaction(''), 'like'); - }); - - it('fallback - unknown', async () => { - assert.strictEqual(await toDbReaction('unknown'), 'like'); - }); -}); -*/ diff --git a/packages/backend/test/resources/25000x25000.png b/packages/backend/test/resources/25000x25000.png deleted file mode 100644 index 0ed4666925..0000000000 Binary files a/packages/backend/test/resources/25000x25000.png and /dev/null differ diff --git a/packages/backend/test/resources/Lenna.jpg b/packages/backend/test/resources/Lenna.jpg deleted file mode 100644 index 6b5b32281c..0000000000 Binary files a/packages/backend/test/resources/Lenna.jpg and /dev/null differ diff --git a/packages/backend/test/resources/Lenna.png b/packages/backend/test/resources/Lenna.png deleted file mode 100644 index 59ef68aabd..0000000000 Binary files a/packages/backend/test/resources/Lenna.png and /dev/null differ diff --git a/packages/backend/test/resources/anime.gif b/packages/backend/test/resources/anime.gif deleted file mode 100644 index 256ba495ce..0000000000 Binary files a/packages/backend/test/resources/anime.gif and /dev/null differ diff --git a/packages/backend/test/resources/anime.png b/packages/backend/test/resources/anime.png deleted file mode 100644 index f13600f7a4..0000000000 Binary files a/packages/backend/test/resources/anime.png and /dev/null differ diff --git a/packages/backend/test/resources/emptyfile b/packages/backend/test/resources/emptyfile deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/packages/backend/test/resources/image.svg b/packages/backend/test/resources/image.svg deleted file mode 100644 index 1e2bf5b5bb..0000000000 --- a/packages/backend/test/resources/image.svg +++ /dev/null @@ -1 +0,0 @@ -<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256"><path fill="#FF40A4" d="M128 80c-16 4-20 24-20 48v16c0 8-8 16-20.3 8 4.3 20 24.3 28 40.3 24s20-24 20-48v-16c0-8 8-16 20.3-8C164 84 144 76 128 80"/><path fill="#FFBF40" d="M192 80c-16 4-20 24-20 48v16c0 8-8 16-20.3 8 4.3 20 24.3 28 40.3 24s20-24 20-48v-16c0-8 8-16 20.3-8C228 84 208 76 192 80"/><path fill="#408EFF" d="M64 80c-16 4-20 24-20 48v16c0 8-8 16-20.3 8C28 172 48 180 64 176s20-24 20-48v-16c0-8 8-16 20.3-8C100 84 80 76 64 80"/></svg> diff --git a/packages/backend/test/resources/rotate.jpg b/packages/backend/test/resources/rotate.jpg deleted file mode 100644 index 477c2baf5b..0000000000 Binary files a/packages/backend/test/resources/rotate.jpg and /dev/null differ diff --git a/packages/backend/test/resources/with-alpha.png b/packages/backend/test/resources/with-alpha.png deleted file mode 100644 index adc8d01805..0000000000 Binary files a/packages/backend/test/resources/with-alpha.png and /dev/null differ diff --git a/packages/backend/test/resources/with-xml-def.svg b/packages/backend/test/resources/with-xml-def.svg deleted file mode 100644 index 90971215a6..0000000000 --- a/packages/backend/test/resources/with-xml-def.svg +++ /dev/null @@ -1,2 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256"><path fill="#FF40A4" d="M128 80c-16 4-20 24-20 48v16c0 8-8 16-20.3 8 4.3 20 24.3 28 40.3 24s20-24 20-48v-16c0-8 8-16 20.3-8C164 84 144 76 128 80"/><path fill="#FFBF40" d="M192 80c-16 4-20 24-20 48v16c0 8-8 16-20.3 8 4.3 20 24.3 28 40.3 24s20-24 20-48v-16c0-8 8-16 20.3-8C228 84 208 76 192 80"/><path fill="#408EFF" d="M64 80c-16 4-20 24-20 48v16c0 8-8 16-20.3 8C28 172 48 180 64 176s20-24 20-48v-16c0-8 8-16 20.3-8C100 84 80 76 64 80"/></svg> diff --git a/packages/backend/test/streaming.ts b/packages/backend/test/streaming.ts deleted file mode 100644 index 3292c66e17..0000000000 --- a/packages/backend/test/streaming.ts +++ /dev/null @@ -1,766 +0,0 @@ -process.env.NODE_ENV = "test"; - -import * as assert from "assert"; -import * as childProcess from "child_process"; -import { Following } from "../src/models/entities/following.js"; -import { - connectStream, - signup, - api, - post, - startServer, - shutdownServer, - initTestDb, - waitFire, -} from "./utils.js"; - -describe("Streaming", () => { - let p: childProcess.ChildProcess; - let Followings: any; - - const follow = async (follower: any, followee: any) => { - await Followings.save({ - id: "a", - createdAt: new Date(), - followerId: follower.id, - followeeId: followee.id, - followerHost: follower.host, - followerInbox: null, - followerSharedInbox: null, - followeeHost: followee.host, - followeeInbox: null, - followeeSharedInbox: null, - }); - }; - - describe("Streaming", () => { - // Local users - let ayano: any; - let kyoko: any; - let chitose: any; - - // Remote users - let akari: any; - let chinatsu: any; - - let kyokoNote: any; - let list: any; - - before(async () => { - p = await startServer(); - const connection = await initTestDb(true); - Followings = connection.getRepository(Following); - - ayano = await signup({ username: "ayano" }); - kyoko = await signup({ username: "kyoko" }); - chitose = await signup({ username: "chitose" }); - - akari = await signup({ username: "akari", host: "example.com" }); - chinatsu = await signup({ username: "chinatsu", host: "example.com" }); - - kyokoNote = await post(kyoko, { text: "foo" }); - - // Follow: ayano => kyoko - await api("following/create", { userId: kyoko.id }, ayano); - - // Follow: ayano => akari - await follow(ayano, akari); - - // List: chitose => ayano, kyoko - list = await api( - "users/lists/create", - { - name: "my list", - }, - chitose, - ).then((x) => x.body); - - await api( - "users/lists/push", - { - listId: list.id, - userId: ayano.id, - }, - chitose, - ); - - await api( - "users/lists/push", - { - listId: list.id, - userId: kyoko.id, - }, - chitose, - ); - }); - - after(async () => { - await shutdownServer(p); - }); - - describe("Events", () => { - it("mention event", async () => { - const fired = await waitFire( - kyoko, - "main", // kyoko:main - () => post(ayano, { text: "foo @kyoko bar" }), // ayano mention => kyoko - (msg) => msg.type === "mention" && msg.body.userId === ayano.id, // wait ayano - ); - - assert.strictEqual(fired, true); - }); - - it("renote event", async () => { - const fired = await waitFire( - kyoko, - "main", // kyoko:main - () => post(ayano, { renoteId: kyokoNote.id }), // ayano renote - (msg) => msg.type === "renote" && msg.body.renoteId === kyokoNote.id, // wait renote - ); - - assert.strictEqual(fired, true); - }); - }); - - describe("Home Timeline", () => { - it("自分の投稿が流れる", async () => { - const fired = await waitFire( - ayano, - "homeTimeline", // ayano:Home - () => api("notes/create", { text: "foo" }, ayano), // ayano posts - (msg) => msg.type === "note" && msg.body.text === "foo", - ); - - assert.strictEqual(fired, true); - }); - - it("フォローしているユーザーの投稿が流れる", async () => { - const fired = await waitFire( - ayano, - "homeTimeline", // ayano:home - () => api("notes/create", { text: "foo" }, kyoko), // kyoko posts - (msg) => msg.type === "note" && msg.body.userId === kyoko.id, // wait kyoko - ); - - assert.strictEqual(fired, true); - }); - - it("フォローしていないユーザーの投稿は流れない", async () => { - const fired = await waitFire( - kyoko, - "homeTimeline", // kyoko:home - () => api("notes/create", { text: "foo" }, ayano), // ayano posts - (msg) => msg.type === "note" && msg.body.userId === ayano.id, // wait ayano - ); - - assert.strictEqual(fired, false); - }); - - it("フォローしているユーザーのダイレクト投稿が流れる", async () => { - const fired = await waitFire( - ayano, - "homeTimeline", // ayano:home - () => - api( - "notes/create", - { - text: "foo", - visibility: "specified", - visibleUserIds: [ayano.id], - }, - kyoko, - ), // kyoko dm => ayano - (msg) => msg.type === "note" && msg.body.userId === kyoko.id, // wait kyoko - ); - - assert.strictEqual(fired, true); - }); - - it("フォローしているユーザーでも自分が指定されていないダイレクト投稿は流れない", async () => { - const fired = await waitFire( - ayano, - "homeTimeline", // ayano:home - () => - api( - "notes/create", - { - text: "foo", - visibility: "specified", - visibleUserIds: [chitose.id], - }, - kyoko, - ), // kyoko dm => chitose - (msg) => msg.type === "note" && msg.body.userId === kyoko.id, // wait kyoko - ); - - assert.strictEqual(fired, false); - }); - }); // Home - - describe("Local Timeline", () => { - it("自分の投稿が流れる", async () => { - const fired = await waitFire( - ayano, - "localTimeline", // ayano:Local - () => api("notes/create", { text: "foo" }, ayano), // ayano posts - (msg) => msg.type === "note" && msg.body.text === "foo", - ); - - assert.strictEqual(fired, true); - }); - - it("フォローしていないローカルユーザーの投稿が流れる", async () => { - const fired = await waitFire( - ayano, - "localTimeline", // ayano:Local - () => api("notes/create", { text: "foo" }, chitose), // chitose posts - (msg) => msg.type === "note" && msg.body.userId === chitose.id, // wait chitose - ); - - assert.strictEqual(fired, true); - }); - - it("リモートユーザーの投稿は流れない", async () => { - const fired = await waitFire( - ayano, - "localTimeline", // ayano:Local - () => api("notes/create", { text: "foo" }, chinatsu), // chinatsu posts - (msg) => msg.type === "note" && msg.body.userId === chinatsu.id, // wait chinatsu - ); - - assert.strictEqual(fired, false); - }); - - it("フォローしてたとしてもリモートユーザーの投稿は流れない", async () => { - const fired = await waitFire( - ayano, - "localTimeline", // ayano:Local - () => api("notes/create", { text: "foo" }, akari), // akari posts - (msg) => msg.type === "note" && msg.body.userId === akari.id, // wait akari - ); - - assert.strictEqual(fired, false); - }); - - it("ホーム指定の投稿は流れない", async () => { - const fired = await waitFire( - ayano, - "localTimeline", // ayano:Local - () => api("notes/create", { text: "foo", visibility: "home" }, kyoko), // kyoko home posts - (msg) => msg.type === "note" && msg.body.userId === kyoko.id, // wait kyoko - ); - - assert.strictEqual(fired, false); - }); - - it("フォローしているローカルユーザーのダイレクト投稿は流れない", async () => { - const fired = await waitFire( - ayano, - "localTimeline", // ayano:Local - () => - api( - "notes/create", - { - text: "foo", - visibility: "specified", - visibleUserIds: [ayano.id], - }, - kyoko, - ), // kyoko DM => ayano - (msg) => msg.type === "note" && msg.body.userId === kyoko.id, // wait kyoko - ); - - assert.strictEqual(fired, false); - }); - - it("フォローしていないローカルユーザーのフォロワー宛て投稿は流れない", async () => { - const fired = await waitFire( - ayano, - "localTimeline", // ayano:Local - () => - api( - "notes/create", - { text: "foo", visibility: "followers" }, - chitose, - ), - (msg) => msg.type === "note" && msg.body.userId === chitose.id, // wait chitose - ); - - assert.strictEqual(fired, false); - }); - }); - - describe("Recommended Timeline", () => { - it("自分の投稿が流れる", async () => { - const fired = await waitFire( - ayano, - "recommendedTimeline", // ayano:Local - () => api("notes/create", { text: "foo" }, ayano), // ayano posts - (msg) => msg.type === "note" && msg.body.text === "foo", - ); - - assert.strictEqual(fired, true); - }); - - it("フォローしていないローカルユーザーの投稿が流れる", async () => { - const fired = await waitFire( - ayano, - "recommendedTimeline", // ayano:Local - () => api("notes/create", { text: "foo" }, chitose), // chitose posts - (msg) => msg.type === "note" && msg.body.userId === chitose.id, // wait chitose - ); - - assert.strictEqual(fired, true); - }); - - it("リモートユーザーの投稿は流れない", async () => { - const fired = await waitFire( - ayano, - "recommendedTimeline", // ayano:Local - () => api("notes/create", { text: "foo" }, chinatsu), // chinatsu posts - (msg) => msg.type === "note" && msg.body.userId === chinatsu.id, // wait chinatsu - ); - - assert.strictEqual(fired, false); - }); - - it("フォローしてたとしてもリモートユーザーの投稿は流れない", async () => { - const fired = await waitFire( - ayano, - "recommendedTimeline", // ayano:Local - () => api("notes/create", { text: "foo" }, akari), // akari posts - (msg) => msg.type === "note" && msg.body.userId === akari.id, // wait akari - ); - - assert.strictEqual(fired, false); - }); - - it("ホーム指定の投稿は流れない", async () => { - const fired = await waitFire( - ayano, - "recommendedTimeline", // ayano:Local - () => api("notes/create", { text: "foo", visibility: "home" }, kyoko), // kyoko home posts - (msg) => msg.type === "note" && msg.body.userId === kyoko.id, // wait kyoko - ); - - assert.strictEqual(fired, false); - }); - - it("フォローしているローカルユーザーのダイレクト投稿は流れない", async () => { - const fired = await waitFire( - ayano, - "recommendedTimeline", // ayano:Local - () => - api( - "notes/create", - { - text: "foo", - visibility: "specified", - visibleUserIds: [ayano.id], - }, - kyoko, - ), // kyoko DM => ayano - (msg) => msg.type === "note" && msg.body.userId === kyoko.id, // wait kyoko - ); - - assert.strictEqual(fired, false); - }); - - it("フォローしていないローカルユーザーのフォロワー宛て投稿は流れない", async () => { - const fired = await waitFire( - ayano, - "recommendedTimeline", // ayano:Local - () => - api( - "notes/create", - { text: "foo", visibility: "followers" }, - chitose, - ), - (msg) => msg.type === "note" && msg.body.userId === chitose.id, // wait chitose - ); - - assert.strictEqual(fired, false); - }); - }); - - describe("Hybrid Timeline", () => { - it("自分の投稿が流れる", async () => { - const fired = await waitFire( - ayano, - "hybridTimeline", // ayano:Hybrid - () => api("notes/create", { text: "foo" }, ayano), // ayano posts - (msg) => msg.type === "note" && msg.body.text === "foo", - ); - - assert.strictEqual(fired, true); - }); - - it("フォローしていないローカルユーザーの投稿が流れる", async () => { - const fired = await waitFire( - ayano, - "hybridTimeline", // ayano:Hybrid - () => api("notes/create", { text: "foo" }, chitose), // chitose posts - (msg) => msg.type === "note" && msg.body.userId === chitose.id, // wait chitose - ); - - assert.strictEqual(fired, true); - }); - - it("フォローしているリモートユーザーの投稿が流れる", async () => { - const fired = await waitFire( - ayano, - "hybridTimeline", // ayano:Hybrid - () => api("notes/create", { text: "foo" }, akari), // akari posts - (msg) => msg.type === "note" && msg.body.userId === akari.id, // wait akari - ); - - assert.strictEqual(fired, true); - }); - - it("フォローしていないリモートユーザーの投稿は流れない", async () => { - const fired = await waitFire( - ayano, - "hybridTimeline", // ayano:Hybrid - () => api("notes/create", { text: "foo" }, chinatsu), // chinatsu posts - (msg) => msg.type === "note" && msg.body.userId === chinatsu.id, // wait chinatsu - ); - - assert.strictEqual(fired, false); - }); - - it("フォローしているユーザーのダイレクト投稿が流れる", async () => { - const fired = await waitFire( - ayano, - "hybridTimeline", // ayano:Hybrid - () => - api( - "notes/create", - { - text: "foo", - visibility: "specified", - visibleUserIds: [ayano.id], - }, - kyoko, - ), - (msg) => msg.type === "note" && msg.body.userId === kyoko.id, // wait kyoko - ); - - assert.strictEqual(fired, true); - }); - - it("フォローしているユーザーのホーム投稿が流れる", async () => { - const fired = await waitFire( - ayano, - "hybridTimeline", // ayano:Hybrid - () => api("notes/create", { text: "foo", visibility: "home" }, kyoko), - (msg) => msg.type === "note" && msg.body.userId === kyoko.id, // wait kyoko - ); - - assert.strictEqual(fired, true); - }); - - it("フォローしていないローカルユーザーのホーム投稿は流れない", async () => { - const fired = await waitFire( - ayano, - "hybridTimeline", // ayano:Hybrid - () => - api("notes/create", { text: "foo", visibility: "home" }, chitose), - (msg) => msg.type === "note" && msg.body.userId === chitose.id, - ); - - assert.strictEqual(fired, false); - }); - - it("フォローしていないローカルユーザーのフォロワー宛て投稿は流れない", () => - async () => { - const fired = await waitFire( - ayano, - "hybridTimeline", // ayano:Hybrid - () => - api( - "notes/create", - { text: "foo", visibility: "followers" }, - chitose, - ), - (msg) => msg.type === "note" && msg.body.userId === chitose.id, - ); - - assert.strictEqual(fired, false); - }); - }); - - describe("Global Timeline", () => { - it("フォローしていないローカルユーザーの投稿が流れる", () => async () => { - const fired = await waitFire( - ayano, - "globalTimeline", // ayano:Global - () => api("notes/create", { text: "foo" }, chitose), // chitose posts - (msg) => msg.type === "note" && msg.body.userId === chitose.id, // wait chitose - ); - - assert.strictEqual(fired, true); - }); - - it("フォローしていないリモートユーザーの投稿が流れる", () => async () => { - const fired = await waitFire( - ayano, - "globalTimeline", // ayano:Global - () => api("notes/create", { text: "foo" }, chinatsu), // chinatsu posts - (msg) => msg.type === "note" && msg.body.userId === chinatsu.id, // wait chinatsu - ); - - assert.strictEqual(fired, true); - }); - - it("ホーム投稿は流れない", () => async () => { - const fired = await waitFire( - ayano, - "globalTimeline", // ayano:Global - () => api("notes/create", { text: "foo", visibility: "home" }, kyoko), // kyoko posts - (msg) => msg.type === "note" && msg.body.userId === kyoko.id, // wait kyoko - ); - - assert.strictEqual(fired, false); - }); - }); - - describe("UserList Timeline", () => { - it("リストに入れているユーザーの投稿が流れる", () => async () => { - const fired = await waitFire( - chitose, - "userList", - () => api("notes/create", { text: "foo" }, ayano), - (msg) => msg.type === "note" && msg.body.userId === ayano.id, - { listId: list.id }, - ); - - assert.strictEqual(fired, true); - }); - - it("リストに入れていないユーザーの投稿は流れない", () => async () => { - const fired = await waitFire( - chitose, - "userList", - () => api("notes/create", { text: "foo" }, chinatsu), - (msg) => msg.type === "note" && msg.body.userId === chinatsu.id, - { listId: list.id }, - ); - - assert.strictEqual(fired, false); - }); - - // #4471 - it("リストに入れているユーザーのダイレクト投稿が流れる", () => - async () => { - const fired = await waitFire( - chitose, - "userList", - () => - api( - "notes/create", - { - text: "foo", - visibility: "specified", - visibleUserIds: [chitose.id], - }, - ayano, - ), - (msg) => msg.type === "note" && msg.body.userId === ayano.id, - { listId: list.id }, - ); - - assert.strictEqual(fired, true); - }); - - // #4335 - it("リストに入れているがフォローはしてないユーザーのフォロワー宛て投稿は流れない", () => - async () => { - const fired = await waitFire( - chitose, - "userList", - () => - api( - "notes/create", - { text: "foo", visibility: "followers" }, - kyoko, - ), - (msg) => msg.type === "note" && msg.body.userId === kyoko.id, - { listId: list.id }, - ); - - assert.strictEqual(fired, false); - }); - }); - - describe("Hashtag Timeline", () => { - it("指定したハッシュタグの投稿が流れる", () => - new Promise<void>(async (done) => { - const ws = await connectStream( - chitose, - "hashtag", - ({ type, body }) => { - if (type == "note") { - assert.deepStrictEqual(body.text, "#foo"); - ws.close(); - done(); - } - }, - { - q: [["foo"]], - }, - ); - - post(chitose, { - text: "#foo", - }); - })); - - it("指定したハッシュタグの投稿が流れる (AND)", () => - new Promise<void>(async (done) => { - let fooCount = 0; - let barCount = 0; - let fooBarCount = 0; - - const ws = await connectStream( - chitose, - "hashtag", - ({ type, body }) => { - if (type == "note") { - if (body.text === "#foo") fooCount++; - if (body.text === "#bar") barCount++; - if (body.text === "#foo #bar") fooBarCount++; - } - }, - { - q: [["foo", "bar"]], - }, - ); - - post(chitose, { - text: "#foo", - }); - - post(chitose, { - text: "#bar", - }); - - post(chitose, { - text: "#foo #bar", - }); - - setTimeout(() => { - assert.strictEqual(fooCount, 0); - assert.strictEqual(barCount, 0); - assert.strictEqual(fooBarCount, 1); - ws.close(); - done(); - }, 3000); - })); - - it("指定したハッシュタグの投稿が流れる (OR)", () => - new Promise<void>(async (done) => { - let fooCount = 0; - let barCount = 0; - let fooBarCount = 0; - let piyoCount = 0; - - const ws = await connectStream( - chitose, - "hashtag", - ({ type, body }) => { - if (type == "note") { - if (body.text === "#foo") fooCount++; - if (body.text === "#bar") barCount++; - if (body.text === "#foo #bar") fooBarCount++; - if (body.text === "#piyo") piyoCount++; - } - }, - { - q: [["foo"], ["bar"]], - }, - ); - - post(chitose, { - text: "#foo", - }); - - post(chitose, { - text: "#bar", - }); - - post(chitose, { - text: "#foo #bar", - }); - - post(chitose, { - text: "#piyo", - }); - - setTimeout(() => { - assert.strictEqual(fooCount, 1); - assert.strictEqual(barCount, 1); - assert.strictEqual(fooBarCount, 1); - assert.strictEqual(piyoCount, 0); - ws.close(); - done(); - }, 3000); - })); - - it("指定したハッシュタグの投稿が流れる (AND + OR)", () => - new Promise<void>(async (done) => { - let fooCount = 0; - let barCount = 0; - let fooBarCount = 0; - let piyoCount = 0; - let waaaCount = 0; - - const ws = await connectStream( - chitose, - "hashtag", - ({ type, body }) => { - if (type == "note") { - if (body.text === "#foo") fooCount++; - if (body.text === "#bar") barCount++; - if (body.text === "#foo #bar") fooBarCount++; - if (body.text === "#piyo") piyoCount++; - if (body.text === "#waaa") waaaCount++; - } - }, - { - q: [["foo", "bar"], ["piyo"]], - }, - ); - - post(chitose, { - text: "#foo", - }); - - post(chitose, { - text: "#bar", - }); - - post(chitose, { - text: "#foo #bar", - }); - - post(chitose, { - text: "#piyo", - }); - - post(chitose, { - text: "#waaa", - }); - - setTimeout(() => { - assert.strictEqual(fooCount, 0); - assert.strictEqual(barCount, 0); - assert.strictEqual(fooBarCount, 1); - assert.strictEqual(piyoCount, 1); - assert.strictEqual(waaaCount, 0); - ws.close(); - done(); - }, 3000); - })); - }); - }); -}); diff --git a/packages/backend/test/thread-mute.ts b/packages/backend/test/thread-mute.ts deleted file mode 100644 index 9b3bb8dfe4..0000000000 --- a/packages/backend/test/thread-mute.ts +++ /dev/null @@ -1,161 +0,0 @@ -process.env.NODE_ENV = "test"; - -import * as assert from "assert"; -import * as childProcess from "child_process"; -import { - async, - signup, - request, - post, - react, - connectStream, - startServer, - shutdownServer, -} from "./utils.js"; - -describe("Note thread mute", () => { - let p: childProcess.ChildProcess; - - let alice: any; - let bob: any; - let carol: any; - - before(async () => { - p = await startServer(); - alice = await signup({ username: "alice" }); - bob = await signup({ username: "bob" }); - carol = await signup({ username: "carol" }); - }); - - after(async () => { - await shutdownServer(p); - }); - - it("notes/mentions にミュートしているスレッドの投稿が含まれない", async(async () => { - const bobNote = await post(bob, { text: "@alice @carol root note" }); - const aliceReply = await post(alice, { - replyId: bobNote.id, - text: "@bob @carol child note", - }); - - await request("/notes/thread-muting/create", { noteId: bobNote.id }, alice); - - const carolReply = await post(carol, { - replyId: bobNote.id, - text: "@bob @alice child note", - }); - const carolReplyWithoutMention = await post(carol, { - replyId: aliceReply.id, - text: "child note", - }); - - const res = await request("/notes/mentions", {}, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(Array.isArray(res.body), true); - assert.strictEqual( - res.body.some((note: any) => note.id === bobNote.id), - false, - ); - assert.strictEqual( - res.body.some((note: any) => note.id === carolReply.id), - false, - ); - assert.strictEqual( - res.body.some((note: any) => note.id === carolReplyWithoutMention.id), - false, - ); - })); - - it("ミュートしているスレッドからメンションされても、hasUnreadMentions が true にならない", async(async () => { - // 状態リセット - await request("/i/read-all-unread-notes", {}, alice); - - const bobNote = await post(bob, { text: "@alice @carol root note" }); - - await request("/notes/thread-muting/create", { noteId: bobNote.id }, alice); - - const carolReply = await post(carol, { - replyId: bobNote.id, - text: "@bob @alice child note", - }); - - const res = await request("/i", {}, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(res.body.hasUnreadMentions, false); - })); - - it("ミュートしているスレッドからメンションされても、ストリームに unreadMention イベントが流れてこない", () => - new Promise(async (done) => { - // 状態リセット - await request("/i/read-all-unread-notes", {}, alice); - - const bobNote = await post(bob, { text: "@alice @carol root note" }); - - await request( - "/notes/thread-muting/create", - { noteId: bobNote.id }, - alice, - ); - - let fired = false; - - const ws = await connectStream(alice, "main", async ({ type, body }) => { - if (type === "unreadMention") { - if (body === bobNote.id) return; - fired = true; - } - }); - - const carolReply = await post(carol, { - replyId: bobNote.id, - text: "@bob @alice child note", - }); - - setTimeout(() => { - assert.strictEqual(fired, false); - ws.close(); - done(); - }, 5000); - })); - - it("i/notifications にミュートしているスレッドの通知が含まれない", async(async () => { - const bobNote = await post(bob, { text: "@alice @carol root note" }); - const aliceReply = await post(alice, { - replyId: bobNote.id, - text: "@bob @carol child note", - }); - - await request("/notes/thread-muting/create", { noteId: bobNote.id }, alice); - - const carolReply = await post(carol, { - replyId: bobNote.id, - text: "@bob @alice child note", - }); - const carolReplyWithoutMention = await post(carol, { - replyId: aliceReply.id, - text: "child note", - }); - - const res = await request("/i/notifications", {}, alice); - - assert.strictEqual(res.status, 200); - assert.strictEqual(Array.isArray(res.body), true); - assert.strictEqual( - res.body.some( - (notification: any) => notification.note.id === carolReply.id, - ), - false, - ); - assert.strictEqual( - res.body.some( - (notification: any) => - notification.note.id === carolReplyWithoutMention.id, - ), - false, - ); - - // NOTE: bobの投稿はスレッドミュート前に行われたため通知に含まれていてもよい - })); -}); diff --git a/packages/backend/test/tsconfig.json b/packages/backend/test/tsconfig.json deleted file mode 100644 index bc7a9968b5..0000000000 --- a/packages/backend/test/tsconfig.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "compilerOptions": { - "allowJs": true, - "noEmitOnError": false, - "noImplicitAny": true, - "noImplicitReturns": true, - "noUnusedParameters": false, - "noUnusedLocals": true, - "noFallthroughCasesInSwitch": true, - "declaration": false, - "sourceMap": true, - "target": "es2021", - "module": "es2020", - "moduleResolution": "node", - "allowSyntheticDefaultImports": true, - "removeComments": false, - "noLib": false, - "strict": true, - "strictNullChecks": true, - "strictPropertyInitialization": false, - "experimentalDecorators": true, - "emitDecoratorMetadata": true, - "resolveJsonModule": true, - "isolatedModules": true, - "baseUrl": "./", - "paths": { - "@/*": ["../src/*"] - }, - "typeRoots": [ - "../node_modules/@types", - "../src/@types" - ], - "lib": [ - "esnext" - ] - }, - "compileOnSave": false, - "include": [ - "./**/*.ts" - ] -} diff --git a/packages/backend/test/user-notes.ts b/packages/backend/test/user-notes.ts deleted file mode 100644 index 86a541c101..0000000000 --- a/packages/backend/test/user-notes.ts +++ /dev/null @@ -1,98 +0,0 @@ -process.env.NODE_ENV = "test"; - -import * as assert from "assert"; -import * as childProcess from "child_process"; -import { - async, - signup, - request, - post, - uploadUrl, - startServer, - shutdownServer, -} from "./utils.js"; - -describe("users/notes", () => { - let p: childProcess.ChildProcess; - - let alice: any; - let jpgNote: any; - let pngNote: any; - let jpgPngNote: any; - - before(async () => { - p = await startServer(); - alice = await signup({ username: "alice" }); - const jpg = await uploadUrl( - alice, - "https://raw.githubusercontent.com/misskey-dev/misskey/develop/packages/backend/test/resources/Lenna.jpg", - ); - const png = await uploadUrl( - alice, - "https://raw.githubusercontent.com/misskey-dev/misskey/develop/packages/backend/test/resources/Lenna.png", - ); - jpgNote = await post(alice, { - fileIds: [jpg.id], - }); - pngNote = await post(alice, { - fileIds: [png.id], - }); - jpgPngNote = await post(alice, { - fileIds: [jpg.id, png.id], - }); - }); - - after(async () => { - await shutdownServer(p); - }); - - it("ファイルタイプ指定 (jpg)", async(async () => { - const res = await request( - "/users/notes", - { - userId: alice.id, - fileType: ["image/jpeg"], - }, - alice, - ); - - assert.strictEqual(res.status, 200); - assert.strictEqual(Array.isArray(res.body), true); - assert.strictEqual(res.body.length, 2); - assert.strictEqual( - res.body.some((note: any) => note.id === jpgNote.id), - true, - ); - assert.strictEqual( - res.body.some((note: any) => note.id === jpgPngNote.id), - true, - ); - })); - - it("ファイルタイプ指定 (jpg or png)", async(async () => { - const res = await request( - "/users/notes", - { - userId: alice.id, - fileType: ["image/jpeg", "image/png"], - }, - alice, - ); - - assert.strictEqual(res.status, 200); - assert.strictEqual(Array.isArray(res.body), true); - assert.strictEqual(res.body.length, 3); - assert.strictEqual( - res.body.some((note: any) => note.id === jpgNote.id), - true, - ); - assert.strictEqual( - res.body.some((note: any) => note.id === pngNote.id), - true, - ); - assert.strictEqual( - res.body.some((note: any) => note.id === jpgPngNote.id), - true, - ); - })); -}); diff --git a/packages/backend/test/utils.ts b/packages/backend/test/utils.ts deleted file mode 100644 index f3f68b2609..0000000000 --- a/packages/backend/test/utils.ts +++ /dev/null @@ -1,403 +0,0 @@ -import * as fs from "node:fs"; -import * as path from "node:path"; -import { fileURLToPath } from "node:url"; -import { dirname } from "node:path"; -import * as childProcess from "child_process"; -import * as http from "node:http"; -import { SIGKILL } from "constants"; -import WebSocket from "ws"; -import * as misskey from "calckey-js"; -import fetch from "node-fetch"; -import FormData from "form-data"; -import { DataSource } from "typeorm"; -import loadConfig from "../src/config/load.js"; -import { entities } from "../src/db/postgre.js"; -import got from "got"; - -const _filename = fileURLToPath(import.meta.url); -const _dirname = dirname(_filename); - -const config = loadConfig(); -export const port = config.port; - -export const async = (fn: Function) => (done: Function) => { - fn().then( - () => { - done(); - }, - (err: Error) => { - done(err); - }, - ); -}; - -export const api = async (endpoint: string, params: any, me?: any) => { - endpoint = endpoint.replace(/^\//, ""); - - const auth = me - ? { - i: me.token, - } - : {}; - - const res = await got<string>(`http://localhost:${port}/api/${endpoint}`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify(Object.assign(auth, params)), - retry: { - limit: 0, - }, - hooks: { - beforeError: [ - (error) => { - const { response } = error; - if (response && response.body) console.warn(response.body); - return error; - }, - ], - }, - }); - - const status = res.statusCode; - const body = res.statusCode !== 204 ? await JSON.parse(res.body) : null; - - return { - status, - body, - }; -}; - -export const request = async ( - endpoint: string, - params: any, - me?: any, -): Promise<{ body: any; status: number }> => { - const auth = me - ? { - i: me.token, - } - : {}; - - const res = await fetch(`http://localhost:${port}/api${endpoint}`, { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify(Object.assign(auth, params)), - }); - - const status = res.status; - const body = res.status !== 204 ? await res.json().catch() : null; - - return { - body, - status, - }; -}; - -export const signup = async (params?: any): Promise<any> => { - const q = Object.assign( - { - username: "test", - password: "test", - }, - params, - ); - - const res = await api("signup", q); - - return res.body; -}; - -export const post = async ( - user: any, - params?: misskey.Endpoints["notes/create"]["req"], -): Promise<misskey.entities.Note> => { - const q = Object.assign( - { - text: "test", - }, - params, - ); - - const res = await api("notes/create", q, user); - - return res.body ? res.body.createdNote : null; -}; - -export const react = async ( - user: any, - note: any, - reaction: string, -): Promise<any> => { - await api( - "notes/reactions/create", - { - noteId: note.id, - reaction: reaction, - }, - user, - ); -}; - -/** - * Upload file - * @param user User - * @param _path Optional, absolute path or relative from ./resources/ - */ -export const uploadFile = async (user: any, _path?: string): Promise<any> => { - const absPath = - _path == null - ? `${_dirname}/resources/Lenna.jpg` - : path.isAbsolute(_path) - ? _path - : `${_dirname}/resources/${_path}`; - - const formData = new FormData() as any; - formData.append("i", user.token); - formData.append("file", fs.createReadStream(absPath)); - formData.append("force", "true"); - - const res = await got<string>( - `http://localhost:${port}/api/drive/files/create`, - { - method: "POST", - body: formData, - retry: { - limit: 0, - }, - }, - ); - - const body = res.statusCode !== 204 ? await JSON.parse(res.body) : null; - - return body; -}; - -export const uploadUrl = async (user: any, url: string) => { - let file: any; - - const ws = await connectStream(user, "main", (msg) => { - if (msg.type === "driveFileCreated") { - file = msg.body; - } - }); - - await api( - "drive/files/upload-from-url", - { - url, - force: true, - }, - user, - ); - - await sleep(5000); - ws.close(); - - return file; -}; - -export function connectStream( - user: any, - channel: string, - listener: (message: Record<string, any>) => any, - params?: any, -): Promise<WebSocket> { - return new Promise((res, rej) => { - const ws = new WebSocket( - `ws://localhost:${port}/streaming?i=${user.token}`, - ); - - ws.on("open", () => { - ws.on("message", (data) => { - const msg = JSON.parse(data.toString()); - if (msg.type === "channel" && msg.body.id === "a") { - listener(msg.body); - } else if (msg.type === "connected" && msg.body.id === "a") { - res(ws); - } - }); - - ws.send( - JSON.stringify({ - type: "connect", - body: { - channel: channel, - id: "a", - pong: true, - params: params, - }, - }), - ); - }); - }); -} - -export const waitFire = async ( - user: any, - channel: string, - trgr: () => any, - cond: (msg: Record<string, any>) => boolean, - params?: any, -) => { - return new Promise<boolean>(async (res, rej) => { - let timer: NodeJS.Timeout; - - let ws: WebSocket; - try { - ws = await connectStream( - user, - channel, - (msg) => { - if (cond(msg)) { - ws.close(); - if (timer) clearTimeout(timer); - res(true); - } - }, - params, - ); - } catch (e) { - rej(e); - } - - if (!ws!) return; - - timer = setTimeout(() => { - ws.close(); - res(false); - }, 3000); - - try { - await trgr(); - } catch (e) { - ws.close(); - if (timer) clearTimeout(timer); - rej(e); - } - }); -}; - -export const simpleGet = async ( - path: string, - accept = "*/*", -): Promise<{ status?: number; type?: string; location?: string }> => { - // node-fetchだと3xxを取れない - return await new Promise((resolve, reject) => { - const req = http.request( - `http://localhost:${port}${path}`, - { - headers: { - Accept: accept, - }, - }, - (res) => { - if (res.statusCode! >= 400) { - reject(res); - } else { - resolve({ - status: res.statusCode, - type: res.headers["content-type"], - location: res.headers.location, - }); - } - }, - ); - - req.end(); - }); -}; - -export function launchServer( - callbackSpawnedProcess: (p: childProcess.ChildProcess) => void, - moreProcess: () => Promise<void> = async () => {}, -) { - return (done: (err?: Error) => any) => { - const p = childProcess.spawn("node", [_dirname + "/../index.js"], { - stdio: ["inherit", "inherit", "inherit", "ipc"], - env: { NODE_ENV: "test", PATH: process.env.PATH }, - }); - callbackSpawnedProcess(p); - p.on("message", (message) => { - if (message === "ok") - moreProcess() - .then(() => done()) - .catch((e) => done(e)); - }); - }; -} - -export async function initTestDb(justBorrow = false, initEntities?: any[]) { - if (process.env.NODE_ENV !== "test") throw "NODE_ENV is not a test"; - - const db = new DataSource({ - type: "postgres", - host: config.db.host, - port: config.db.port, - username: config.db.user, - password: config.db.pass, - database: config.db.db, - synchronize: true && !justBorrow, - dropSchema: true && !justBorrow, - entities: initEntities || entities, - }); - - await db.initialize(); - - return db; -} - -export function startServer( - timeout = 60 * 1000, -): Promise<childProcess.ChildProcess> { - return new Promise((res, rej) => { - const t = setTimeout(() => { - p.kill(SIGKILL); - rej("timeout to start"); - }, timeout); - - const p = childProcess.spawn("node", [_dirname + "/../built/index.js"], { - stdio: ["inherit", "inherit", "inherit", "ipc"], - env: { NODE_ENV: "test", PATH: process.env.PATH }, - }); - - p.on("error", (e) => rej(e)); - - p.on("message", (message) => { - if (message === "ok") { - clearTimeout(t); - res(p); - } - }); - }); -} - -export function shutdownServer( - p: childProcess.ChildProcess, - timeout = 20 * 1000, -) { - return new Promise((res, rej) => { - const t = setTimeout(() => { - p.kill(SIGKILL); - res("force exit"); - }, timeout); - - p.once("exit", () => { - clearTimeout(t); - res("exited"); - }); - - p.kill(); - }); -} - -export function sleep(msec: number) { - return new Promise<void>((res) => { - setTimeout(() => { - res(); - }, msec); - }); -} diff --git a/packages/backend/tsconfig.json b/packages/backend/tsconfig.json deleted file mode 100644 index 692d7b95b7..0000000000 --- a/packages/backend/tsconfig.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "compilerOptions": { - "allowJs": true, - "noEmitOnError": false, - "noImplicitAny": true, - "noImplicitReturns": true, - "noUnusedParameters": false, - "noUnusedLocals": false, - "noFallthroughCasesInSwitch": true, - "declaration": false, - "sourceMap": false, - "target": "es2021", - "module": "es2020", - "moduleResolution": "node", - "allowSyntheticDefaultImports": true, - "removeComments": false, - "noLib": false, - "strict": true, - "strictNullChecks": true, - "strictPropertyInitialization": false, - "experimentalDecorators": true, - "emitDecoratorMetadata": true, - "resolveJsonModule": true, - "isolatedModules": false, - "rootDir": "./src", - "baseUrl": "./", - "paths": { - "@/*": [ - "./src/*" - ] - }, - "outDir": "./built", - "types": [ - "node" - ], - "typeRoots": [ - "./node_modules/@types", - "./src/@types" - ], - "lib": [ - "esnext" - ] - }, - "compileOnSave": false, - "include": [ - "./src/**/*.ts" - ], -}