egirlskey/packages/backend/src/core/activitypub/ApInboxService.ts

774 lines
24 KiB
TypeScript
Raw Normal View History

/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
2022-09-17 18:27:08 +00:00
import { Inject, Injectable } from '@nestjs/common';
enhance: account migration (#10592) * copy block and mute then create follow and unfollow jobs * copy block and mute and update lists when detecting an account has moved * no need to care promise orders * refactor updating actor and target * automatically accept if a locked account had accepted an old account * fix exception format * prevent the old account from calling some endpoints * do not unfollow when moving * adjust following and follower counts * check movedToUri when receiving a follow request * skip if no need to adjust * Revert "disable account migration" This reverts commit 2321214c98591bcfe1385c1ab5bf0ff7b471ae1d. * fix translation specifier * fix checking alsoKnownAs and uri * fix updating account * fix refollowing locked account * decrease followersCount if followed by the old account * adjust following and followers counts when unfollowing * fix copying mutings * prohibit moved account from moving again * fix move service * allow app creation after moving * fix lint * remove unnecessary field * fix cache update * add e2e test * add e2e test of accepting the new account automatically * force follow if any error happens * remove unnecessary joins * use Array.map instead of for const of * ユーザーリストの移行は追加のみを行う * nanka iroiro * fix misskey-js? * :v: * 移行を行ったアカウントからのフォローリクエストの自動許可を調整 * newUriを外に出す * newUriを外に出す2 * clean up * fix newUri * prevent moving if the destination account has already moved * set alsoKnownAs via /i/update * fix database initialization * add return type * prohibit updating alsoKnownAs after moving * skip to add to alsoKnownAs if toUrl is known * skip adding to the list if it already has * use Acct.parse instead * rename error code * :art: * 制限を5から10に緩和 * movedTo(Uri), alsoKnownAsはユーザーidを返すように * test api res * fix * 元アカウントはミュートし続ける * :art: * unfollow * fix * getUserUriをUserEntityServiceに * ? * job! * :art: * instance => server * accountMovedShort, forbiddenBecauseYouAreMigrated * accountMovedShort * fix test * import, pin禁止 * 実績を凍結する * clean up * :v: * change message * ブロック, フォロー, ミュート, リストのインポートファイルの制限を32MiBに * Revert "ブロック, フォロー, ミュート, リストのインポートファイルの制限を32MiBに" This reverts commit 3bd7be35d8aa455cb01ae58f8172a71a50485db1. * validateAlsoKnownAs * 移行後2時間以内はインポート可能なファイルサイズを拡大 * clean up * どうせactorをupdatePersonで更新するならupdatePersonしか移行処理を発行しないことにする * handle error? * リモートからの移行処理の条件を是正 * log, port * fix * fix * enhance(dev): non-production環境でhttpサーバー間でもユーザー、ノートの連合が可能なように * refactor (use checkHttps) * MISSKEY_WEBFINGER_USE_HTTP * Environment Variable readme * NEVER USE IN PRODUCTION * fix punyHost * fix indent * fix * experimental --------- Co-authored-by: tamaina <tamaina@hotmail.co.jp> Co-authored-by: syuilo <Syuilotan@yahoo.co.jp>
2023-04-29 15:09:29 +00:00
import { In } from 'typeorm';
2022-09-17 18:27:08 +00:00
import { DI } from '@/di-symbols.js';
2022-09-20 20:33:11 +00:00
import type { Config } from '@/config.js';
2022-09-17 18:27:08 +00:00
import { UserFollowingService } from '@/core/UserFollowingService.js';
import { ReactionService } from '@/core/ReactionService.js';
import { RelayService } from '@/core/RelayService.js';
import { NotePiningService } from '@/core/NotePiningService.js';
import { UserBlockingService } from '@/core/UserBlockingService.js';
import { NoteDeleteService } from '@/core/NoteDeleteService.js';
import { NoteCreateService } from '@/core/NoteCreateService.js';
import { concat, toArray, toSingle, unique } from '@/misc/prelude/array.js';
import { AppLockService } from '@/core/AppLockService.js';
import type Logger from '@/logger.js';
import { MetaService } from '@/core/MetaService.js';
import { IdService } from '@/core/IdService.js';
import { StatusError } from '@/misc/status-error.js';
import { UtilityService } from '@/core/UtilityService.js';
import { NoteEntityService } from '@/core/entities/NoteEntityService.js';
import { UserEntityService } from '@/core/entities/UserEntityService.js';
import { QueueService } from '@/core/QueueService.js';
import type { UsersRepository, NotesRepository, FollowingsRepository, AbuseUserReportsRepository, FollowRequestsRepository } from '@/models/_.js';
2023-02-12 09:47:30 +00:00
import { bindThis } from '@/decorators.js';
import type { MiRemoteUser } from '@/models/User.js';
import { isNotNull } from '@/misc/is-not-null.js';
refactor(backend): `core/activitypub` (#11247) * eslint: `explicit-function-return-type` * eslint: `no-unnecessary-condition` * eslint: `eslint-disable-next-line` * eslint: `no-unused-vars` * eslint: `comma-dangle` * eslint: `import/order` * cleanup: unnecessary non-null assertion * cleanup: `IActivity`に`actor`は常に存在するようなので * cleanup: unnecessary `as` * cleanup: unnecessary `Promise.resolve` * cleanup * refactor: `String.prototype.match()`である必要がない部分をよりシンプルな書き方に変更 * refactor: よりよい型定義 * refactor: よりよい型定義 - `LdSignature`の`normalize`メソッドでの使われ方から、 - `data`引数の型定義を`any`から`JsonLdDocument`へ修正 - `getLoader`メソッドの返り値の型定義の一部を`any`から`RemoteDocument`へ修正 - `contextUrl`が不正な値(`null`)となっていたことが判明したため`undefined`へ修正 - `document`の型と合わせるために`CONTEXTS`の型定義の一部を`unknown`から`JsonLd`へ修正 - とりあえず`satisfies`を使用 - `document`の型と合わせるために`fetchDocument`メソッドの返り値の型定義の一部を`unknown`から`JsonLd`へ修正 - どうしようもなく`as`を使用 * refactor: 型ガードを使うことでnon-null assertionをやめた * refactor: non-null assertionをやめた `.filter()`で行っている型ガードなどの文脈から、より適しているだろうと思われる書き方に変更した。 * refactor: 型ガードを使うことで`as`をやめた * refactor: `as`をやめた * refactor: よりよい型定義 - `id`は`null`とのunionになっていたが、`null`を渡している場面はなかった - またおそらくこのメソッドは`IOrderedCollection`を返すため、そちらに合わせて`null`とのunionをやめた - `IOrderedCollection`とはまだ型に相違がある - `totalItems`をコメントや使われ方を元に`number`へ推論 * refactor: `for-of` -> `Array.prototype.map` * refactor: `delete`演算子を使わない形に
2023-07-13 03:48:34 +00:00
import { getApHrefNullable, getApId, getApIds, getApType, isAccept, isActor, isAdd, isAnnounce, isBlock, isCollection, isCollectionOrOrderedCollection, isCreate, isDelete, isFlag, isFollow, isLike, isMove, isPost, isReject, isRemove, isTombstone, isUndo, isUpdate, validActor, validPost } from './type.js';
2022-09-18 18:08:54 +00:00
import { ApNoteService } from './models/ApNoteService.js';
2022-09-17 18:27:08 +00:00
import { ApLoggerService } from './ApLoggerService.js';
import { ApDbResolverService } from './ApDbResolverService.js';
import { ApResolverService } from './ApResolverService.js';
import { ApAudienceService } from './ApAudienceService.js';
import { ApPersonService } from './models/ApPersonService.js';
import { ApQuestionService } from './models/ApQuestionService.js';
import { GlobalEventService } from '@/core/GlobalEventService.js';
2022-09-17 18:27:08 +00:00
import type { Resolver } from './ApResolverService.js';
import type { IAccept, IAdd, IAnnounce, IBlock, ICreate, IDelete, IFlag, IFollow, ILike, IObject, IReject, IRemove, IUndo, IUpdate, IMove } from './type.js';
2022-09-17 18:27:08 +00:00
@Injectable()
export class ApInboxService {
2022-09-18 18:11:50 +00:00
private logger: Logger;
2022-09-17 18:27:08 +00:00
constructor(
@Inject(DI.config)
private config: Config,
@Inject(DI.usersRepository)
private usersRepository: UsersRepository,
@Inject(DI.notesRepository)
private notesRepository: NotesRepository,
@Inject(DI.followingsRepository)
private followingsRepository: FollowingsRepository,
@Inject(DI.abuseUserReportsRepository)
private abuseUserReportsRepository: AbuseUserReportsRepository,
@Inject(DI.followRequestsRepository)
private followRequestsRepository: FollowRequestsRepository,
private userEntityService: UserEntityService,
private noteEntityService: NoteEntityService,
private utilityService: UtilityService,
private idService: IdService,
private metaService: MetaService,
private userFollowingService: UserFollowingService,
private apAudienceService: ApAudienceService,
private reactionService: ReactionService,
private relayService: RelayService,
private notePiningService: NotePiningService,
private userBlockingService: UserBlockingService,
private noteCreateService: NoteCreateService,
private noteDeleteService: NoteDeleteService,
private appLockService: AppLockService,
private apResolverService: ApResolverService,
private apDbResolverService: ApDbResolverService,
private apLoggerService: ApLoggerService,
2022-09-18 18:08:54 +00:00
private apNoteService: ApNoteService,
2022-09-17 18:27:08 +00:00
private apPersonService: ApPersonService,
private apQuestionService: ApQuestionService,
private queueService: QueueService,
private globalEventService: GlobalEventService,
2022-09-17 18:27:08 +00:00
) {
2022-09-18 18:11:50 +00:00
this.logger = this.apLoggerService.logger;
2022-09-17 18:27:08 +00:00
}
@bindThis
public async performActivity(actor: MiRemoteUser, activity: IObject): Promise<void> {
2022-09-17 18:27:08 +00:00
if (isCollectionOrOrderedCollection(activity)) {
const resolver = this.apResolverService.createResolver();
for (const item of toArray(isCollection(activity) ? activity.items : activity.orderedItems)) {
const act = await resolver.resolve(item);
try {
await this.performOneActivity(actor, act);
} catch (err) {
if (err instanceof Error || typeof err === 'string') {
2022-09-18 18:11:50 +00:00
this.logger.error(err);
} else {
throw err;
2022-09-17 18:27:08 +00:00
}
}
}
} else {
await this.performOneActivity(actor, activity);
}
// ついでにリモートユーザーの情報が古かったら更新しておく
if (actor.uri) {
if (actor.lastFetchedAt == null || Date.now() - actor.lastFetchedAt.getTime() > 1000 * 60 * 60 * 24) {
setImmediate(() => {
refactor(backend): `core/activitypub` (#11247) * eslint: `explicit-function-return-type` * eslint: `no-unnecessary-condition` * eslint: `eslint-disable-next-line` * eslint: `no-unused-vars` * eslint: `comma-dangle` * eslint: `import/order` * cleanup: unnecessary non-null assertion * cleanup: `IActivity`に`actor`は常に存在するようなので * cleanup: unnecessary `as` * cleanup: unnecessary `Promise.resolve` * cleanup * refactor: `String.prototype.match()`である必要がない部分をよりシンプルな書き方に変更 * refactor: よりよい型定義 * refactor: よりよい型定義 - `LdSignature`の`normalize`メソッドでの使われ方から、 - `data`引数の型定義を`any`から`JsonLdDocument`へ修正 - `getLoader`メソッドの返り値の型定義の一部を`any`から`RemoteDocument`へ修正 - `contextUrl`が不正な値(`null`)となっていたことが判明したため`undefined`へ修正 - `document`の型と合わせるために`CONTEXTS`の型定義の一部を`unknown`から`JsonLd`へ修正 - とりあえず`satisfies`を使用 - `document`の型と合わせるために`fetchDocument`メソッドの返り値の型定義の一部を`unknown`から`JsonLd`へ修正 - どうしようもなく`as`を使用 * refactor: 型ガードを使うことでnon-null assertionをやめた * refactor: non-null assertionをやめた `.filter()`で行っている型ガードなどの文脈から、より適しているだろうと思われる書き方に変更した。 * refactor: 型ガードを使うことで`as`をやめた * refactor: `as`をやめた * refactor: よりよい型定義 - `id`は`null`とのunionになっていたが、`null`を渡している場面はなかった - またおそらくこのメソッドは`IOrderedCollection`を返すため、そちらに合わせて`null`とのunionをやめた - `IOrderedCollection`とはまだ型に相違がある - `totalItems`をコメントや使われ方を元に`number`へ推論 * refactor: `for-of` -> `Array.prototype.map` * refactor: `delete`演算子を使わない形に
2023-07-13 03:48:34 +00:00
this.apPersonService.updatePerson(actor.uri);
2022-09-17 18:27:08 +00:00
});
}
}
}
@bindThis
public async performOneActivity(actor: MiRemoteUser, activity: IObject): Promise<void> {
2022-09-17 18:27:08 +00:00
if (actor.isSuspended) return;
if (isCreate(activity)) {
2022-09-18 18:11:50 +00:00
await this.create(actor, activity);
2022-09-17 18:27:08 +00:00
} else if (isDelete(activity)) {
2022-09-18 18:11:50 +00:00
await this.delete(actor, activity);
2022-09-17 18:27:08 +00:00
} else if (isUpdate(activity)) {
2022-09-18 18:11:50 +00:00
await this.update(actor, activity);
2022-09-17 18:27:08 +00:00
} else if (isFollow(activity)) {
2022-09-18 18:11:50 +00:00
await this.follow(actor, activity);
2022-09-17 18:27:08 +00:00
} else if (isAccept(activity)) {
2022-09-18 18:11:50 +00:00
await this.accept(actor, activity);
2022-09-17 18:27:08 +00:00
} else if (isReject(activity)) {
2022-09-18 18:11:50 +00:00
await this.reject(actor, activity);
2022-09-17 18:27:08 +00:00
} else if (isAdd(activity)) {
2022-09-18 18:11:50 +00:00
await this.add(actor, activity).catch(err => this.logger.error(err));
2022-09-17 18:27:08 +00:00
} else if (isRemove(activity)) {
2022-09-18 18:11:50 +00:00
await this.remove(actor, activity).catch(err => this.logger.error(err));
2022-09-17 18:27:08 +00:00
} else if (isAnnounce(activity)) {
2022-09-18 18:11:50 +00:00
await this.announce(actor, activity);
2022-09-17 18:27:08 +00:00
} else if (isLike(activity)) {
2022-09-18 18:11:50 +00:00
await this.like(actor, activity);
2022-09-17 18:27:08 +00:00
} else if (isUndo(activity)) {
2022-09-18 18:11:50 +00:00
await this.undo(actor, activity);
2022-09-17 18:27:08 +00:00
} else if (isBlock(activity)) {
2022-09-18 18:11:50 +00:00
await this.block(actor, activity);
2022-09-17 18:27:08 +00:00
} else if (isFlag(activity)) {
2022-09-18 18:11:50 +00:00
await this.flag(actor, activity);
} else if (isMove(activity)) {
enhance: account migration (#10592) * copy block and mute then create follow and unfollow jobs * copy block and mute and update lists when detecting an account has moved * no need to care promise orders * refactor updating actor and target * automatically accept if a locked account had accepted an old account * fix exception format * prevent the old account from calling some endpoints * do not unfollow when moving * adjust following and follower counts * check movedToUri when receiving a follow request * skip if no need to adjust * Revert "disable account migration" This reverts commit 2321214c98591bcfe1385c1ab5bf0ff7b471ae1d. * fix translation specifier * fix checking alsoKnownAs and uri * fix updating account * fix refollowing locked account * decrease followersCount if followed by the old account * adjust following and followers counts when unfollowing * fix copying mutings * prohibit moved account from moving again * fix move service * allow app creation after moving * fix lint * remove unnecessary field * fix cache update * add e2e test * add e2e test of accepting the new account automatically * force follow if any error happens * remove unnecessary joins * use Array.map instead of for const of * ユーザーリストの移行は追加のみを行う * nanka iroiro * fix misskey-js? * :v: * 移行を行ったアカウントからのフォローリクエストの自動許可を調整 * newUriを外に出す * newUriを外に出す2 * clean up * fix newUri * prevent moving if the destination account has already moved * set alsoKnownAs via /i/update * fix database initialization * add return type * prohibit updating alsoKnownAs after moving * skip to add to alsoKnownAs if toUrl is known * skip adding to the list if it already has * use Acct.parse instead * rename error code * :art: * 制限を5から10に緩和 * movedTo(Uri), alsoKnownAsはユーザーidを返すように * test api res * fix * 元アカウントはミュートし続ける * :art: * unfollow * fix * getUserUriをUserEntityServiceに * ? * job! * :art: * instance => server * accountMovedShort, forbiddenBecauseYouAreMigrated * accountMovedShort * fix test * import, pin禁止 * 実績を凍結する * clean up * :v: * change message * ブロック, フォロー, ミュート, リストのインポートファイルの制限を32MiBに * Revert "ブロック, フォロー, ミュート, リストのインポートファイルの制限を32MiBに" This reverts commit 3bd7be35d8aa455cb01ae58f8172a71a50485db1. * validateAlsoKnownAs * 移行後2時間以内はインポート可能なファイルサイズを拡大 * clean up * どうせactorをupdatePersonで更新するならupdatePersonしか移行処理を発行しないことにする * handle error? * リモートからの移行処理の条件を是正 * log, port * fix * fix * enhance(dev): non-production環境でhttpサーバー間でもユーザー、ノートの連合が可能なように * refactor (use checkHttps) * MISSKEY_WEBFINGER_USE_HTTP * Environment Variable readme * NEVER USE IN PRODUCTION * fix punyHost * fix indent * fix * experimental --------- Co-authored-by: tamaina <tamaina@hotmail.co.jp> Co-authored-by: syuilo <Syuilotan@yahoo.co.jp>
2023-04-29 15:09:29 +00:00
await this.move(actor, activity);
2022-09-17 18:27:08 +00:00
} else {
this.logger.warn(`unrecognized activity type: ${activity.type}`);
2022-09-17 18:27:08 +00:00
}
}
@bindThis
private async follow(actor: MiRemoteUser, activity: IFollow): Promise<string> {
2022-09-17 18:27:08 +00:00
const followee = await this.apDbResolverService.getUserFromApId(activity.object);
2022-09-17 18:27:08 +00:00
if (followee == null) {
return 'skip: followee not found';
}
2022-09-17 18:27:08 +00:00
if (followee.host != null) {
return 'skip: フォローしようとしているユーザーはローカルユーザーではありません';
}
enhance: account migration (#10592) * copy block and mute then create follow and unfollow jobs * copy block and mute and update lists when detecting an account has moved * no need to care promise orders * refactor updating actor and target * automatically accept if a locked account had accepted an old account * fix exception format * prevent the old account from calling some endpoints * do not unfollow when moving * adjust following and follower counts * check movedToUri when receiving a follow request * skip if no need to adjust * Revert "disable account migration" This reverts commit 2321214c98591bcfe1385c1ab5bf0ff7b471ae1d. * fix translation specifier * fix checking alsoKnownAs and uri * fix updating account * fix refollowing locked account * decrease followersCount if followed by the old account * adjust following and followers counts when unfollowing * fix copying mutings * prohibit moved account from moving again * fix move service * allow app creation after moving * fix lint * remove unnecessary field * fix cache update * add e2e test * add e2e test of accepting the new account automatically * force follow if any error happens * remove unnecessary joins * use Array.map instead of for const of * ユーザーリストの移行は追加のみを行う * nanka iroiro * fix misskey-js? * :v: * 移行を行ったアカウントからのフォローリクエストの自動許可を調整 * newUriを外に出す * newUriを外に出す2 * clean up * fix newUri * prevent moving if the destination account has already moved * set alsoKnownAs via /i/update * fix database initialization * add return type * prohibit updating alsoKnownAs after moving * skip to add to alsoKnownAs if toUrl is known * skip adding to the list if it already has * use Acct.parse instead * rename error code * :art: * 制限を5から10に緩和 * movedTo(Uri), alsoKnownAsはユーザーidを返すように * test api res * fix * 元アカウントはミュートし続ける * :art: * unfollow * fix * getUserUriをUserEntityServiceに * ? * job! * :art: * instance => server * accountMovedShort, forbiddenBecauseYouAreMigrated * accountMovedShort * fix test * import, pin禁止 * 実績を凍結する * clean up * :v: * change message * ブロック, フォロー, ミュート, リストのインポートファイルの制限を32MiBに * Revert "ブロック, フォロー, ミュート, リストのインポートファイルの制限を32MiBに" This reverts commit 3bd7be35d8aa455cb01ae58f8172a71a50485db1. * validateAlsoKnownAs * 移行後2時間以内はインポート可能なファイルサイズを拡大 * clean up * どうせactorをupdatePersonで更新するならupdatePersonしか移行処理を発行しないことにする * handle error? * リモートからの移行処理の条件を是正 * log, port * fix * fix * enhance(dev): non-production環境でhttpサーバー間でもユーザー、ノートの連合が可能なように * refactor (use checkHttps) * MISSKEY_WEBFINGER_USE_HTTP * Environment Variable readme * NEVER USE IN PRODUCTION * fix punyHost * fix indent * fix * experimental --------- Co-authored-by: tamaina <tamaina@hotmail.co.jp> Co-authored-by: syuilo <Syuilotan@yahoo.co.jp>
2023-04-29 15:09:29 +00:00
// don't queue because the sender may attempt again when timeout
新規にフォローした人のwithRepliesをtrueにする機能を追加 (#12048) * feat: add defaultWithReplies to MiUser * feat: use defaultWithReplies when creating MiFollowing * feat: update defaultWithReplies from API * feat: return defaultWithReplies as a part of $i * feat(frontend): configure defaultWithReplies * docs(changelog): 新規にフォローした人のをデフォルトでTL二追加できるように * fix: typo * style: fix lint failure * chore: improve UI text * chore: make optional params of UserFollowingService.follow() object * chore: UserFollowingService.follow() accept withReplies * chore: add withReplies to MiFollowRequest * chore: process withReplies for follow request * feat: accept withReplies on 'following/create' endpoint * feat: store defaultWithReplies in client store * Revert "feat: return defaultWithReplies as a part of $i" This reverts commit f2cc4fe6 * Revert "feat: update defaultWithReplies from API" This reverts commit 95e3cee6 * Revert "feat: add defaultWithReplies to MiUser" This reverts commit 9f5ab14d7063532de2b049bc2ed40a15658168f5. * feat: configuring withReplies in import-following * feat(frontend): configure withReplies * fix(frontend): incorrectly showRepliesToOthersInTimeline can be shown * fix(backend): withReplies of following/create not working * fix(frontend): importFollowing error * fix: withReplies is not working with follow import * fix(frontend): use v-model * style: fix lint --------- Co-authored-by: Sayamame-beans <61457993+sayamame-beans@users.noreply.github.com> Co-authored-by: syuilo <syuilotan@yahoo.co.jp>
2023-10-17 11:56:17 +00:00
await this.userFollowingService.follow(actor, followee, { requestId: activity.id });
2022-09-17 18:27:08 +00:00
return 'ok';
}
@bindThis
private async like(actor: MiRemoteUser, activity: ILike): Promise<string> {
2022-09-17 18:27:08 +00:00
const targetUri = getApId(activity.object);
const note = await this.apNoteService.fetchNote(targetUri);
if (!note) return `skip: target note not found ${targetUri}`;
await this.apNoteService.extractEmojis(activity.tag ?? [], actor.host).catch(() => null);
2022-09-18 18:03:11 +00:00
return await this.reactionService.create(actor, note, activity._misskey_reaction ?? activity.content ?? activity.name).catch(err => {
if (err.id === '51c42bb4-931a-456b-bff7-e5a8a70dd298') {
2022-09-17 18:27:08 +00:00
return 'skip: already reacted';
} else {
2022-09-18 18:03:11 +00:00
throw err;
2022-09-17 18:27:08 +00:00
}
}).then(() => 'ok');
}
@bindThis
private async accept(actor: MiRemoteUser, activity: IAccept): Promise<string> {
2022-09-17 18:27:08 +00:00
const uri = activity.id ?? activity;
2022-09-18 18:11:50 +00:00
this.logger.info(`Accept: ${uri}`);
2022-09-17 18:27:08 +00:00
const resolver = this.apResolverService.createResolver();
2022-09-17 18:27:08 +00:00
const object = await resolver.resolve(activity.object).catch(err => {
2022-09-18 18:11:50 +00:00
this.logger.error(`Resolution failed: ${err}`);
2022-09-17 18:27:08 +00:00
throw err;
});
2022-09-18 18:11:50 +00:00
if (isFollow(object)) return await this.acceptFollow(actor, object);
2022-09-17 18:27:08 +00:00
return `skip: Unknown Accept type: ${getApType(object)}`;
}
@bindThis
private async acceptFollow(actor: MiRemoteUser, activity: IFollow): Promise<string> {
2022-09-17 18:27:08 +00:00
// ※ activityはこっちから投げたフォローリクエストなので、activity.actorは存在するローカルユーザーである必要がある
const follower = await this.apDbResolverService.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 this.relayService.relayAccepted(match[1]);
}
await this.userFollowingService.acceptFollowRequest(actor, follower);
return 'ok';
}
@bindThis
private async add(actor: MiRemoteUser, activity: IAdd): Promise<void> {
refactor(backend): `core/activitypub` (#11247) * eslint: `explicit-function-return-type` * eslint: `no-unnecessary-condition` * eslint: `eslint-disable-next-line` * eslint: `no-unused-vars` * eslint: `comma-dangle` * eslint: `import/order` * cleanup: unnecessary non-null assertion * cleanup: `IActivity`に`actor`は常に存在するようなので * cleanup: unnecessary `as` * cleanup: unnecessary `Promise.resolve` * cleanup * refactor: `String.prototype.match()`である必要がない部分をよりシンプルな書き方に変更 * refactor: よりよい型定義 * refactor: よりよい型定義 - `LdSignature`の`normalize`メソッドでの使われ方から、 - `data`引数の型定義を`any`から`JsonLdDocument`へ修正 - `getLoader`メソッドの返り値の型定義の一部を`any`から`RemoteDocument`へ修正 - `contextUrl`が不正な値(`null`)となっていたことが判明したため`undefined`へ修正 - `document`の型と合わせるために`CONTEXTS`の型定義の一部を`unknown`から`JsonLd`へ修正 - とりあえず`satisfies`を使用 - `document`の型と合わせるために`fetchDocument`メソッドの返り値の型定義の一部を`unknown`から`JsonLd`へ修正 - どうしようもなく`as`を使用 * refactor: 型ガードを使うことでnon-null assertionをやめた * refactor: non-null assertionをやめた `.filter()`で行っている型ガードなどの文脈から、より適しているだろうと思われる書き方に変更した。 * refactor: 型ガードを使うことで`as`をやめた * refactor: `as`をやめた * refactor: よりよい型定義 - `id`は`null`とのunionになっていたが、`null`を渡している場面はなかった - またおそらくこのメソッドは`IOrderedCollection`を返すため、そちらに合わせて`null`とのunionをやめた - `IOrderedCollection`とはまだ型に相違がある - `totalItems`をコメントや使われ方を元に`number`へ推論 * refactor: `for-of` -> `Array.prototype.map` * refactor: `delete`演算子を使わない形に
2023-07-13 03:48:34 +00:00
if (actor.uri !== activity.actor) {
2022-09-17 18:27:08 +00:00
throw new Error('invalid actor');
}
2022-09-17 18:27:08 +00:00
if (activity.target == null) {
throw new Error('target is null');
}
2022-09-17 18:27:08 +00:00
if (activity.target === actor.featured) {
const note = await this.apNoteService.resolveNote(activity.object);
if (note == null) throw new Error('note not found');
await this.notePiningService.addPinned(actor, note.id);
return;
}
2022-09-17 18:27:08 +00:00
throw new Error(`unknown target: ${activity.target}`);
}
@bindThis
private async announce(actor: MiRemoteUser, activity: IAnnounce): Promise<void> {
2022-09-17 18:27:08 +00:00
const uri = getApId(activity);
2022-09-18 18:11:50 +00:00
this.logger.info(`Announce: ${uri}`);
2022-09-17 18:27:08 +00:00
const targetUri = getApId(activity.object);
await this.announceNote(actor, activity, targetUri);
2022-09-17 18:27:08 +00:00
}
@bindThis
private async announceNote(actor: MiRemoteUser, activity: IAnnounce, targetUri: string): Promise<void> {
2022-09-17 18:27:08 +00:00
const uri = getApId(activity);
if (actor.isSuspended) {
return;
}
// アナウンス先をブロックしてたら中断
const meta = await this.metaService.fetch();
if (this.utilityService.isBlockedHost(meta.blockedHosts, this.utilityService.extractDbHost(uri))) return;
2022-09-17 18:27:08 +00:00
const unlock = await this.appLockService.getApLock(uri);
try {
refactor(backend): `core/activitypub` (#11247) * eslint: `explicit-function-return-type` * eslint: `no-unnecessary-condition` * eslint: `eslint-disable-next-line` * eslint: `no-unused-vars` * eslint: `comma-dangle` * eslint: `import/order` * cleanup: unnecessary non-null assertion * cleanup: `IActivity`に`actor`は常に存在するようなので * cleanup: unnecessary `as` * cleanup: unnecessary `Promise.resolve` * cleanup * refactor: `String.prototype.match()`である必要がない部分をよりシンプルな書き方に変更 * refactor: よりよい型定義 * refactor: よりよい型定義 - `LdSignature`の`normalize`メソッドでの使われ方から、 - `data`引数の型定義を`any`から`JsonLdDocument`へ修正 - `getLoader`メソッドの返り値の型定義の一部を`any`から`RemoteDocument`へ修正 - `contextUrl`が不正な値(`null`)となっていたことが判明したため`undefined`へ修正 - `document`の型と合わせるために`CONTEXTS`の型定義の一部を`unknown`から`JsonLd`へ修正 - とりあえず`satisfies`を使用 - `document`の型と合わせるために`fetchDocument`メソッドの返り値の型定義の一部を`unknown`から`JsonLd`へ修正 - どうしようもなく`as`を使用 * refactor: 型ガードを使うことでnon-null assertionをやめた * refactor: non-null assertionをやめた `.filter()`で行っている型ガードなどの文脈から、より適しているだろうと思われる書き方に変更した。 * refactor: 型ガードを使うことで`as`をやめた * refactor: `as`をやめた * refactor: よりよい型定義 - `id`は`null`とのunionになっていたが、`null`を渡している場面はなかった - またおそらくこのメソッドは`IOrderedCollection`を返すため、そちらに合わせて`null`とのunionをやめた - `IOrderedCollection`とはまだ型に相違がある - `totalItems`をコメントや使われ方を元に`number`へ推論 * refactor: `for-of` -> `Array.prototype.map` * refactor: `delete`演算子を使わない形に
2023-07-13 03:48:34 +00:00
// 既に同じURIを持つものが登録されていないかチェック
2022-09-17 18:27:08 +00:00
const exist = await this.apNoteService.fetchNote(uri);
if (exist) {
return;
}
// Announce対象をresolve
let renote;
try {
renote = await this.apNoteService.resolveNote(targetUri);
2022-09-23 23:41:27 +00:00
if (renote == null) throw new Error('announce target is null');
2022-09-17 18:27:08 +00:00
} catch (err) {
2022-09-23 23:41:27 +00:00
// 対象が4xxならスキップ
2022-09-17 18:27:08 +00:00
if (err instanceof StatusError) {
if (!err.isRetryable) {
2022-09-18 18:11:50 +00:00
this.logger.warn(`Ignored announce target ${targetUri} - ${err.statusCode}`);
2022-09-17 18:27:08 +00:00
return;
}
refactor(backend): `core/activitypub` (#11247) * eslint: `explicit-function-return-type` * eslint: `no-unnecessary-condition` * eslint: `eslint-disable-next-line` * eslint: `no-unused-vars` * eslint: `comma-dangle` * eslint: `import/order` * cleanup: unnecessary non-null assertion * cleanup: `IActivity`に`actor`は常に存在するようなので * cleanup: unnecessary `as` * cleanup: unnecessary `Promise.resolve` * cleanup * refactor: `String.prototype.match()`である必要がない部分をよりシンプルな書き方に変更 * refactor: よりよい型定義 * refactor: よりよい型定義 - `LdSignature`の`normalize`メソッドでの使われ方から、 - `data`引数の型定義を`any`から`JsonLdDocument`へ修正 - `getLoader`メソッドの返り値の型定義の一部を`any`から`RemoteDocument`へ修正 - `contextUrl`が不正な値(`null`)となっていたことが判明したため`undefined`へ修正 - `document`の型と合わせるために`CONTEXTS`の型定義の一部を`unknown`から`JsonLd`へ修正 - とりあえず`satisfies`を使用 - `document`の型と合わせるために`fetchDocument`メソッドの返り値の型定義の一部を`unknown`から`JsonLd`へ修正 - どうしようもなく`as`を使用 * refactor: 型ガードを使うことでnon-null assertionをやめた * refactor: non-null assertionをやめた `.filter()`で行っている型ガードなどの文脈から、より適しているだろうと思われる書き方に変更した。 * refactor: 型ガードを使うことで`as`をやめた * refactor: `as`をやめた * refactor: よりよい型定義 - `id`は`null`とのunionになっていたが、`null`を渡している場面はなかった - またおそらくこのメソッドは`IOrderedCollection`を返すため、そちらに合わせて`null`とのunionをやめた - `IOrderedCollection`とはまだ型に相違がある - `totalItems`をコメントや使われ方を元に`number`へ推論 * refactor: `for-of` -> `Array.prototype.map` * refactor: `delete`演算子を使わない形に
2023-07-13 03:48:34 +00:00
this.logger.warn(`Error in announce target ${targetUri} - ${err.statusCode}`);
2022-09-17 18:27:08 +00:00
}
throw err;
}
2022-09-23 23:41:27 +00:00
if (!await this.noteEntityService.isVisibleForMe(renote, actor.id)) {
this.logger.warn('skip: invalid actor for this activity');
return;
}
2022-09-17 18:27:08 +00:00
2022-09-18 18:11:50 +00:00
this.logger.info(`Creating the (Re)Note: ${uri}`);
2022-09-17 18:27:08 +00:00
const activityAudience = await this.apAudienceService.parseAudience(actor, activity.to, activity.cc);
const createdAt = activity.published ? new Date(activity.published) : null;
if (createdAt && createdAt < this.idService.parse(renote.id).date) {
this.logger.warn('skip: malformed createdAt');
return;
}
2022-09-17 18:27:08 +00:00
await this.noteCreateService.create(actor, {
createdAt,
2022-09-17 18:27:08 +00:00
renote,
visibility: activityAudience.visibility,
visibleUsers: activityAudience.visibleUsers,
uri,
});
} finally {
unlock();
}
}
@bindThis
private async block(actor: MiRemoteUser, activity: IBlock): Promise<string> {
2022-09-17 18:27:08 +00:00
// ※ activity.objectにブロック対象があり、それは存在するローカルユーザーのはず
const blockee = await this.apDbResolverService.getUserFromApId(activity.object);
if (blockee == null) {
return 'skip: blockee not found';
}
if (blockee.host != null) {
return 'skip: ブロックしようとしているユーザーはローカルユーザーではありません';
}
await this.userBlockingService.block(await this.usersRepository.findOneByOrFail({ id: actor.id }), await this.usersRepository.findOneByOrFail({ id: blockee.id }));
return 'ok';
}
@bindThis
private async create(actor: MiRemoteUser, activity: ICreate): Promise<void> {
2022-09-17 18:27:08 +00:00
const uri = getApId(activity);
2022-09-18 18:11:50 +00:00
this.logger.info(`Create: ${uri}`);
2022-09-17 18:27:08 +00:00
// 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 = this.apResolverService.createResolver();
const object = await resolver.resolve(activity.object).catch(e => {
2022-09-18 18:11:50 +00:00
this.logger.error(`Resolution failed: ${e}`);
2022-09-17 18:27:08 +00:00
throw e;
});
if (isPost(object)) {
await this.createNote(resolver, actor, object, false, activity);
2022-09-17 18:27:08 +00:00
} else {
2022-09-18 18:11:50 +00:00
this.logger.warn(`Unknown type: ${getApType(object)}`);
2022-09-17 18:27:08 +00:00
}
}
@bindThis
private async createNote(resolver: Resolver, actor: MiRemoteUser, note: IObject, silent = false, activity?: ICreate): Promise<string> {
2022-09-17 18:27:08 +00:00
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 (this.utilityService.extractDbHost(actor.uri) !== this.utilityService.extractDbHost(note.id)) {
return 'skip: host in actor.uri !== note.id';
}
}
}
const unlock = await this.appLockService.getApLock(uri);
try {
const exist = await this.apNoteService.fetchNote(note);
if (exist) return 'skip: note exists';
await this.apNoteService.createNote(note, resolver, silent);
return 'ok';
2022-09-18 18:03:11 +00:00
} catch (err) {
if (err instanceof StatusError && !err.isRetryable) {
2022-09-18 18:03:11 +00:00
return `skip ${err.statusCode}`;
2022-09-17 18:27:08 +00:00
} else {
2022-09-18 18:03:11 +00:00
throw err;
2022-09-17 18:27:08 +00:00
}
} finally {
unlock();
}
}
@bindThis
private async delete(actor: MiRemoteUser, activity: IDelete): Promise<string> {
refactor(backend): `core/activitypub` (#11247) * eslint: `explicit-function-return-type` * eslint: `no-unnecessary-condition` * eslint: `eslint-disable-next-line` * eslint: `no-unused-vars` * eslint: `comma-dangle` * eslint: `import/order` * cleanup: unnecessary non-null assertion * cleanup: `IActivity`に`actor`は常に存在するようなので * cleanup: unnecessary `as` * cleanup: unnecessary `Promise.resolve` * cleanup * refactor: `String.prototype.match()`である必要がない部分をよりシンプルな書き方に変更 * refactor: よりよい型定義 * refactor: よりよい型定義 - `LdSignature`の`normalize`メソッドでの使われ方から、 - `data`引数の型定義を`any`から`JsonLdDocument`へ修正 - `getLoader`メソッドの返り値の型定義の一部を`any`から`RemoteDocument`へ修正 - `contextUrl`が不正な値(`null`)となっていたことが判明したため`undefined`へ修正 - `document`の型と合わせるために`CONTEXTS`の型定義の一部を`unknown`から`JsonLd`へ修正 - とりあえず`satisfies`を使用 - `document`の型と合わせるために`fetchDocument`メソッドの返り値の型定義の一部を`unknown`から`JsonLd`へ修正 - どうしようもなく`as`を使用 * refactor: 型ガードを使うことでnon-null assertionをやめた * refactor: non-null assertionをやめた `.filter()`で行っている型ガードなどの文脈から、より適しているだろうと思われる書き方に変更した。 * refactor: 型ガードを使うことで`as`をやめた * refactor: `as`をやめた * refactor: よりよい型定義 - `id`は`null`とのunionになっていたが、`null`を渡している場面はなかった - またおそらくこのメソッドは`IOrderedCollection`を返すため、そちらに合わせて`null`とのunionをやめた - `IOrderedCollection`とはまだ型に相違がある - `totalItems`をコメントや使われ方を元に`number`へ推論 * refactor: `for-of` -> `Array.prototype.map` * refactor: `delete`演算子を使わない形に
2023-07-13 03:48:34 +00:00
if (actor.uri !== activity.actor) {
2022-09-17 18:27:08 +00:00
throw new Error('invalid actor');
}
2022-09-17 18:27:08 +00:00
// 削除対象objectのtype
let formerType: string | undefined;
2022-09-17 18:27:08 +00:00
if (typeof activity.object === 'string') {
// typeが不明だけど、どうせ消えてるのでremote resolveしない
formerType = undefined;
} else {
refactor(backend): `core/activitypub` (#11247) * eslint: `explicit-function-return-type` * eslint: `no-unnecessary-condition` * eslint: `eslint-disable-next-line` * eslint: `no-unused-vars` * eslint: `comma-dangle` * eslint: `import/order` * cleanup: unnecessary non-null assertion * cleanup: `IActivity`に`actor`は常に存在するようなので * cleanup: unnecessary `as` * cleanup: unnecessary `Promise.resolve` * cleanup * refactor: `String.prototype.match()`である必要がない部分をよりシンプルな書き方に変更 * refactor: よりよい型定義 * refactor: よりよい型定義 - `LdSignature`の`normalize`メソッドでの使われ方から、 - `data`引数の型定義を`any`から`JsonLdDocument`へ修正 - `getLoader`メソッドの返り値の型定義の一部を`any`から`RemoteDocument`へ修正 - `contextUrl`が不正な値(`null`)となっていたことが判明したため`undefined`へ修正 - `document`の型と合わせるために`CONTEXTS`の型定義の一部を`unknown`から`JsonLd`へ修正 - とりあえず`satisfies`を使用 - `document`の型と合わせるために`fetchDocument`メソッドの返り値の型定義の一部を`unknown`から`JsonLd`へ修正 - どうしようもなく`as`を使用 * refactor: 型ガードを使うことでnon-null assertionをやめた * refactor: non-null assertionをやめた `.filter()`で行っている型ガードなどの文脈から、より適しているだろうと思われる書き方に変更した。 * refactor: 型ガードを使うことで`as`をやめた * refactor: `as`をやめた * refactor: よりよい型定義 - `id`は`null`とのunionになっていたが、`null`を渡している場面はなかった - またおそらくこのメソッドは`IOrderedCollection`を返すため、そちらに合わせて`null`とのunionをやめた - `IOrderedCollection`とはまだ型に相違がある - `totalItems`をコメントや使われ方を元に`number`へ推論 * refactor: `for-of` -> `Array.prototype.map` * refactor: `delete`演算子を使わない形に
2023-07-13 03:48:34 +00:00
const object = activity.object;
2022-09-17 18:27:08 +00:00
if (isTombstone(object)) {
formerType = toSingle(object.formerType);
} else {
formerType = toSingle(object.type);
}
}
2022-09-17 18:27:08 +00:00
const uri = getApId(activity.object);
2022-09-17 18:27:08 +00:00
// type不明でもactorとobjectが同じならばそれはPersonに違いない
if (!formerType && actor.uri === uri) {
formerType = 'Person';
}
2022-09-17 18:27:08 +00:00
// それでもなかったらおそらくNote
if (!formerType) {
formerType = 'Note';
}
2022-09-17 18:27:08 +00:00
if (validPost.includes(formerType)) {
2022-09-18 18:11:50 +00:00
return await this.deleteNote(actor, uri);
2022-09-17 18:27:08 +00:00
} else if (validActor.includes(formerType)) {
2022-09-18 18:11:50 +00:00
return await this.deleteActor(actor, uri);
2022-09-17 18:27:08 +00:00
} else {
return `Unknown type ${formerType}`;
}
}
@bindThis
private async deleteActor(actor: MiRemoteUser, uri: string): Promise<string> {
2022-09-18 18:11:50 +00:00
this.logger.info(`Deleting the Actor: ${uri}`);
2022-09-17 18:27:08 +00:00
if (actor.uri !== uri) {
return `skip: delete actor ${actor.uri} !== ${uri}`;
}
const user = await this.usersRepository.findOneBy({ id: actor.id });
if (user == null) {
return 'skip: actor not found';
} else if (user.isDeleted) {
return 'skip: already deleted';
2022-09-17 18:27:08 +00:00
}
2022-09-17 18:27:08 +00:00
const job = await this.queueService.createDeleteAccountJob(actor);
2022-09-17 18:27:08 +00:00
await this.usersRepository.update(actor.id, {
isDeleted: true,
});
this.globalEventService.publishInternalEvent('remoteUserUpdated', { id: actor.id });
2022-09-17 18:27:08 +00:00
return `ok: queued ${job.name} ${job.id}`;
}
@bindThis
private async deleteNote(actor: MiRemoteUser, uri: string): Promise<string> {
2022-09-18 18:11:50 +00:00
this.logger.info(`Deleting the Note: ${uri}`);
2022-09-17 18:27:08 +00:00
const unlock = await this.appLockService.getApLock(uri);
2022-09-17 18:27:08 +00:00
try {
const note = await this.apDbResolverService.getNoteFromApId(uri);
2022-09-17 18:27:08 +00:00
if (note == null) {
return 'message not found';
2022-09-17 18:27:08 +00:00
}
2022-09-17 18:27:08 +00:00
if (note.userId !== actor.id) {
return '投稿を削除しようとしているユーザーは投稿の作成者ではありません';
}
2022-09-17 18:27:08 +00:00
await this.noteDeleteService.delete(actor, note);
return 'ok: note deleted';
} finally {
unlock();
}
}
@bindThis
private async flag(actor: MiRemoteUser, activity: IFlag): Promise<string> {
2022-09-17 18:27:08 +00:00
// objectは `(User|Note) | (User|Note)[]` だけど、全パターンDBスキーマと対応させられないので
// 対象ユーザーは一番最初のユーザー として あとはコメントとして格納する
const uris = getApIds(activity.object);
refactor(backend): `core/activitypub` (#11247) * eslint: `explicit-function-return-type` * eslint: `no-unnecessary-condition` * eslint: `eslint-disable-next-line` * eslint: `no-unused-vars` * eslint: `comma-dangle` * eslint: `import/order` * cleanup: unnecessary non-null assertion * cleanup: `IActivity`に`actor`は常に存在するようなので * cleanup: unnecessary `as` * cleanup: unnecessary `Promise.resolve` * cleanup * refactor: `String.prototype.match()`である必要がない部分をよりシンプルな書き方に変更 * refactor: よりよい型定義 * refactor: よりよい型定義 - `LdSignature`の`normalize`メソッドでの使われ方から、 - `data`引数の型定義を`any`から`JsonLdDocument`へ修正 - `getLoader`メソッドの返り値の型定義の一部を`any`から`RemoteDocument`へ修正 - `contextUrl`が不正な値(`null`)となっていたことが判明したため`undefined`へ修正 - `document`の型と合わせるために`CONTEXTS`の型定義の一部を`unknown`から`JsonLd`へ修正 - とりあえず`satisfies`を使用 - `document`の型と合わせるために`fetchDocument`メソッドの返り値の型定義の一部を`unknown`から`JsonLd`へ修正 - どうしようもなく`as`を使用 * refactor: 型ガードを使うことでnon-null assertionをやめた * refactor: non-null assertionをやめた `.filter()`で行っている型ガードなどの文脈から、より適しているだろうと思われる書き方に変更した。 * refactor: 型ガードを使うことで`as`をやめた * refactor: `as`をやめた * refactor: よりよい型定義 - `id`は`null`とのunionになっていたが、`null`を渡している場面はなかった - またおそらくこのメソッドは`IOrderedCollection`を返すため、そちらに合わせて`null`とのunionをやめた - `IOrderedCollection`とはまだ型に相違がある - `totalItems`をコメントや使われ方を元に`number`へ推論 * refactor: `for-of` -> `Array.prototype.map` * refactor: `delete`演算子を使わない形に
2023-07-13 03:48:34 +00:00
const userIds = uris
.filter(uri => uri.startsWith(this.config.url + '/users/'))
.map(uri => uri.split('/').at(-1))
.filter(isNotNull);
2022-09-17 18:27:08 +00:00
const users = await this.usersRepository.findBy({
id: In(userIds),
});
if (users.length < 1) return 'skip';
await this.abuseUserReportsRepository.insert({
id: this.idService.gen(),
2022-09-17 18:27:08 +00:00
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';
}
@bindThis
private async reject(actor: MiRemoteUser, activity: IReject): Promise<string> {
2022-09-17 18:27:08 +00:00
const uri = activity.id ?? activity;
2022-09-18 18:11:50 +00:00
this.logger.info(`Reject: ${uri}`);
2022-09-17 18:27:08 +00:00
const resolver = this.apResolverService.createResolver();
const object = await resolver.resolve(activity.object).catch(e => {
2022-09-18 18:11:50 +00:00
this.logger.error(`Resolution failed: ${e}`);
2022-09-17 18:27:08 +00:00
throw e;
});
2022-09-18 18:11:50 +00:00
if (isFollow(object)) return await this.rejectFollow(actor, object);
2022-09-17 18:27:08 +00:00
return `skip: Unknown Reject type: ${getApType(object)}`;
}
@bindThis
private async rejectFollow(actor: MiRemoteUser, activity: IFollow): Promise<string> {
2022-09-17 18:27:08 +00:00
// ※ activityはこっちから投げたフォローリクエストなので、activity.actorは存在するローカルユーザーである必要がある
2022-09-17 18:27:08 +00:00
const follower = await this.apDbResolverService.getUserFromApId(activity.actor);
2022-09-17 18:27:08 +00:00
if (follower == null) {
return 'skip: follower not found';
}
2022-09-17 18:27:08 +00:00
if (!this.userEntityService.isLocalUser(follower)) {
return 'skip: follower is not a local user';
}
2022-09-17 18:27:08 +00:00
// relay
const match = activity.id?.match(/follow-relay\/(\w+)/);
if (match) {
return await this.relayService.relayRejected(match[1]);
}
2022-09-17 18:27:08 +00:00
await this.userFollowingService.remoteReject(actor, follower);
return 'ok';
}
@bindThis
private async remove(actor: MiRemoteUser, activity: IRemove): Promise<void> {
refactor(backend): `core/activitypub` (#11247) * eslint: `explicit-function-return-type` * eslint: `no-unnecessary-condition` * eslint: `eslint-disable-next-line` * eslint: `no-unused-vars` * eslint: `comma-dangle` * eslint: `import/order` * cleanup: unnecessary non-null assertion * cleanup: `IActivity`に`actor`は常に存在するようなので * cleanup: unnecessary `as` * cleanup: unnecessary `Promise.resolve` * cleanup * refactor: `String.prototype.match()`である必要がない部分をよりシンプルな書き方に変更 * refactor: よりよい型定義 * refactor: よりよい型定義 - `LdSignature`の`normalize`メソッドでの使われ方から、 - `data`引数の型定義を`any`から`JsonLdDocument`へ修正 - `getLoader`メソッドの返り値の型定義の一部を`any`から`RemoteDocument`へ修正 - `contextUrl`が不正な値(`null`)となっていたことが判明したため`undefined`へ修正 - `document`の型と合わせるために`CONTEXTS`の型定義の一部を`unknown`から`JsonLd`へ修正 - とりあえず`satisfies`を使用 - `document`の型と合わせるために`fetchDocument`メソッドの返り値の型定義の一部を`unknown`から`JsonLd`へ修正 - どうしようもなく`as`を使用 * refactor: 型ガードを使うことでnon-null assertionをやめた * refactor: non-null assertionをやめた `.filter()`で行っている型ガードなどの文脈から、より適しているだろうと思われる書き方に変更した。 * refactor: 型ガードを使うことで`as`をやめた * refactor: `as`をやめた * refactor: よりよい型定義 - `id`は`null`とのunionになっていたが、`null`を渡している場面はなかった - またおそらくこのメソッドは`IOrderedCollection`を返すため、そちらに合わせて`null`とのunionをやめた - `IOrderedCollection`とはまだ型に相違がある - `totalItems`をコメントや使われ方を元に`number`へ推論 * refactor: `for-of` -> `Array.prototype.map` * refactor: `delete`演算子を使わない形に
2023-07-13 03:48:34 +00:00
if (actor.uri !== activity.actor) {
2022-09-17 18:27:08 +00:00
throw new Error('invalid actor');
}
2022-09-17 18:27:08 +00:00
if (activity.target == null) {
throw new Error('target is null');
}
2022-09-17 18:27:08 +00:00
if (activity.target === actor.featured) {
const note = await this.apNoteService.resolveNote(activity.object);
if (note == null) throw new Error('note not found');
await this.notePiningService.removePinned(actor, note.id);
return;
}
2022-09-17 18:27:08 +00:00
throw new Error(`unknown target: ${activity.target}`);
}
@bindThis
private async undo(actor: MiRemoteUser, activity: IUndo): Promise<string> {
refactor(backend): `core/activitypub` (#11247) * eslint: `explicit-function-return-type` * eslint: `no-unnecessary-condition` * eslint: `eslint-disable-next-line` * eslint: `no-unused-vars` * eslint: `comma-dangle` * eslint: `import/order` * cleanup: unnecessary non-null assertion * cleanup: `IActivity`に`actor`は常に存在するようなので * cleanup: unnecessary `as` * cleanup: unnecessary `Promise.resolve` * cleanup * refactor: `String.prototype.match()`である必要がない部分をよりシンプルな書き方に変更 * refactor: よりよい型定義 * refactor: よりよい型定義 - `LdSignature`の`normalize`メソッドでの使われ方から、 - `data`引数の型定義を`any`から`JsonLdDocument`へ修正 - `getLoader`メソッドの返り値の型定義の一部を`any`から`RemoteDocument`へ修正 - `contextUrl`が不正な値(`null`)となっていたことが判明したため`undefined`へ修正 - `document`の型と合わせるために`CONTEXTS`の型定義の一部を`unknown`から`JsonLd`へ修正 - とりあえず`satisfies`を使用 - `document`の型と合わせるために`fetchDocument`メソッドの返り値の型定義の一部を`unknown`から`JsonLd`へ修正 - どうしようもなく`as`を使用 * refactor: 型ガードを使うことでnon-null assertionをやめた * refactor: non-null assertionをやめた `.filter()`で行っている型ガードなどの文脈から、より適しているだろうと思われる書き方に変更した。 * refactor: 型ガードを使うことで`as`をやめた * refactor: `as`をやめた * refactor: よりよい型定義 - `id`は`null`とのunionになっていたが、`null`を渡している場面はなかった - またおそらくこのメソッドは`IOrderedCollection`を返すため、そちらに合わせて`null`とのunionをやめた - `IOrderedCollection`とはまだ型に相違がある - `totalItems`をコメントや使われ方を元に`number`へ推論 * refactor: `for-of` -> `Array.prototype.map` * refactor: `delete`演算子を使わない形に
2023-07-13 03:48:34 +00:00
if (actor.uri !== activity.actor) {
2022-09-17 18:27:08 +00:00
throw new Error('invalid actor');
}
2022-09-17 18:27:08 +00:00
const uri = activity.id ?? activity;
2022-09-18 18:11:50 +00:00
this.logger.info(`Undo: ${uri}`);
2022-09-17 18:27:08 +00:00
const resolver = this.apResolverService.createResolver();
2022-09-17 18:27:08 +00:00
const object = await resolver.resolve(activity.object).catch(e => {
2022-09-18 18:11:50 +00:00
this.logger.error(`Resolution failed: ${e}`);
2022-09-17 18:27:08 +00:00
throw e;
});
enhance: account migration (#10592) * copy block and mute then create follow and unfollow jobs * copy block and mute and update lists when detecting an account has moved * no need to care promise orders * refactor updating actor and target * automatically accept if a locked account had accepted an old account * fix exception format * prevent the old account from calling some endpoints * do not unfollow when moving * adjust following and follower counts * check movedToUri when receiving a follow request * skip if no need to adjust * Revert "disable account migration" This reverts commit 2321214c98591bcfe1385c1ab5bf0ff7b471ae1d. * fix translation specifier * fix checking alsoKnownAs and uri * fix updating account * fix refollowing locked account * decrease followersCount if followed by the old account * adjust following and followers counts when unfollowing * fix copying mutings * prohibit moved account from moving again * fix move service * allow app creation after moving * fix lint * remove unnecessary field * fix cache update * add e2e test * add e2e test of accepting the new account automatically * force follow if any error happens * remove unnecessary joins * use Array.map instead of for const of * ユーザーリストの移行は追加のみを行う * nanka iroiro * fix misskey-js? * :v: * 移行を行ったアカウントからのフォローリクエストの自動許可を調整 * newUriを外に出す * newUriを外に出す2 * clean up * fix newUri * prevent moving if the destination account has already moved * set alsoKnownAs via /i/update * fix database initialization * add return type * prohibit updating alsoKnownAs after moving * skip to add to alsoKnownAs if toUrl is known * skip adding to the list if it already has * use Acct.parse instead * rename error code * :art: * 制限を5から10に緩和 * movedTo(Uri), alsoKnownAsはユーザーidを返すように * test api res * fix * 元アカウントはミュートし続ける * :art: * unfollow * fix * getUserUriをUserEntityServiceに * ? * job! * :art: * instance => server * accountMovedShort, forbiddenBecauseYouAreMigrated * accountMovedShort * fix test * import, pin禁止 * 実績を凍結する * clean up * :v: * change message * ブロック, フォロー, ミュート, リストのインポートファイルの制限を32MiBに * Revert "ブロック, フォロー, ミュート, リストのインポートファイルの制限を32MiBに" This reverts commit 3bd7be35d8aa455cb01ae58f8172a71a50485db1. * validateAlsoKnownAs * 移行後2時間以内はインポート可能なファイルサイズを拡大 * clean up * どうせactorをupdatePersonで更新するならupdatePersonしか移行処理を発行しないことにする * handle error? * リモートからの移行処理の条件を是正 * log, port * fix * fix * enhance(dev): non-production環境でhttpサーバー間でもユーザー、ノートの連合が可能なように * refactor (use checkHttps) * MISSKEY_WEBFINGER_USE_HTTP * Environment Variable readme * NEVER USE IN PRODUCTION * fix punyHost * fix indent * fix * experimental --------- Co-authored-by: tamaina <tamaina@hotmail.co.jp> Co-authored-by: syuilo <Syuilotan@yahoo.co.jp>
2023-04-29 15:09:29 +00:00
// don't queue because the sender may attempt again when timeout
2022-09-18 18:11:50 +00:00
if (isFollow(object)) return await this.undoFollow(actor, object);
if (isBlock(object)) return await this.undoBlock(actor, object);
if (isLike(object)) return await this.undoLike(actor, object);
if (isAnnounce(object)) return await this.undoAnnounce(actor, object);
if (isAccept(object)) return await this.undoAccept(actor, object);
2022-09-17 18:27:08 +00:00
return `skip: unknown object type ${getApType(object)}`;
}
@bindThis
private async undoAccept(actor: MiRemoteUser, activity: IAccept): Promise<string> {
2022-09-17 18:27:08 +00:00
const follower = await this.apDbResolverService.getUserFromApId(activity.object);
if (follower == null) {
return 'skip: follower not found';
}
const isFollowing = await this.followingsRepository.exists({
where: {
followerId: follower.id,
followeeId: actor.id,
},
2022-09-17 18:27:08 +00:00
});
if (isFollowing) {
2022-09-17 18:27:08 +00:00
await this.userFollowingService.unfollow(follower, actor);
return 'ok: unfollowed';
}
2022-09-17 18:27:08 +00:00
return 'skip: フォローされていない';
}
@bindThis
private async undoAnnounce(actor: MiRemoteUser, activity: IAnnounce): Promise<string> {
2022-09-17 18:27:08 +00:00
const uri = getApId(activity);
const note = await this.notesRepository.findOneBy({
uri,
userId: actor.id,
});
if (!note) return 'skip: no such Announce';
await this.noteDeleteService.delete(actor, note);
return 'ok: deleted';
}
@bindThis
private async undoBlock(actor: MiRemoteUser, activity: IBlock): Promise<string> {
2022-09-17 18:27:08 +00:00
const blockee = await this.apDbResolverService.getUserFromApId(activity.object);
if (blockee == null) {
return 'skip: blockee not found';
}
if (blockee.host != null) {
return 'skip: ブロック解除しようとしているユーザーはローカルユーザーではありません';
}
2023-02-13 06:28:07 +00:00
await this.userBlockingService.unblock(await this.usersRepository.findOneByOrFail({ id: actor.id }), blockee);
2022-09-17 18:27:08 +00:00
return 'ok';
}
@bindThis
private async undoFollow(actor: MiRemoteUser, activity: IFollow): Promise<string> {
2022-09-17 18:27:08 +00:00
const followee = await this.apDbResolverService.getUserFromApId(activity.object);
if (followee == null) {
return 'skip: followee not found';
}
if (followee.host != null) {
return 'skip: フォロー解除しようとしているユーザーはローカルユーザーではありません';
}
const requestExist = await this.followRequestsRepository.exists({
where: {
followerId: actor.id,
followeeId: followee.id,
},
2022-09-17 18:27:08 +00:00
});
const isFollowing = await this.followingsRepository.exists({
where: {
followerId: actor.id,
followeeId: followee.id,
},
2022-09-17 18:27:08 +00:00
});
if (requestExist) {
2022-09-17 18:27:08 +00:00
await this.userFollowingService.cancelFollowRequest(followee, actor);
return 'ok: follow request canceled';
}
if (isFollowing) {
2022-09-17 18:27:08 +00:00
await this.userFollowingService.unfollow(actor, followee);
return 'ok: unfollowed';
}
return 'skip: リクエストもフォローもされていない';
}
@bindThis
private async undoLike(actor: MiRemoteUser, activity: ILike): Promise<string> {
2022-09-17 18:27:08 +00:00
const targetUri = getApId(activity.object);
const note = await this.apNoteService.fetchNote(targetUri);
if (!note) return `skip: target note not found ${targetUri}`;
await this.reactionService.delete(actor, note).catch(e => {
if (e.id === '60527ec9-b4cb-4a88-a6bd-32d3ad26817d') return;
throw e;
});
return 'ok';
}
@bindThis
private async update(actor: MiRemoteUser, activity: IUpdate): Promise<string> {
refactor(backend): `core/activitypub` (#11247) * eslint: `explicit-function-return-type` * eslint: `no-unnecessary-condition` * eslint: `eslint-disable-next-line` * eslint: `no-unused-vars` * eslint: `comma-dangle` * eslint: `import/order` * cleanup: unnecessary non-null assertion * cleanup: `IActivity`に`actor`は常に存在するようなので * cleanup: unnecessary `as` * cleanup: unnecessary `Promise.resolve` * cleanup * refactor: `String.prototype.match()`である必要がない部分をよりシンプルな書き方に変更 * refactor: よりよい型定義 * refactor: よりよい型定義 - `LdSignature`の`normalize`メソッドでの使われ方から、 - `data`引数の型定義を`any`から`JsonLdDocument`へ修正 - `getLoader`メソッドの返り値の型定義の一部を`any`から`RemoteDocument`へ修正 - `contextUrl`が不正な値(`null`)となっていたことが判明したため`undefined`へ修正 - `document`の型と合わせるために`CONTEXTS`の型定義の一部を`unknown`から`JsonLd`へ修正 - とりあえず`satisfies`を使用 - `document`の型と合わせるために`fetchDocument`メソッドの返り値の型定義の一部を`unknown`から`JsonLd`へ修正 - どうしようもなく`as`を使用 * refactor: 型ガードを使うことでnon-null assertionをやめた * refactor: non-null assertionをやめた `.filter()`で行っている型ガードなどの文脈から、より適しているだろうと思われる書き方に変更した。 * refactor: 型ガードを使うことで`as`をやめた * refactor: `as`をやめた * refactor: よりよい型定義 - `id`は`null`とのunionになっていたが、`null`を渡している場面はなかった - またおそらくこのメソッドは`IOrderedCollection`を返すため、そちらに合わせて`null`とのunionをやめた - `IOrderedCollection`とはまだ型に相違がある - `totalItems`をコメントや使われ方を元に`number`へ推論 * refactor: `for-of` -> `Array.prototype.map` * refactor: `delete`演算子を使わない形に
2023-07-13 03:48:34 +00:00
if (actor.uri !== activity.actor) {
2022-09-17 18:27:08 +00:00
return 'skip: invalid actor';
}
2022-09-18 18:11:50 +00:00
this.logger.debug('Update');
2022-09-17 18:27:08 +00:00
const resolver = this.apResolverService.createResolver();
2022-09-17 18:27:08 +00:00
const object = await resolver.resolve(activity.object).catch(e => {
2022-09-18 18:11:50 +00:00
this.logger.error(`Resolution failed: ${e}`);
2022-09-17 18:27:08 +00:00
throw e;
});
2022-09-17 18:27:08 +00:00
if (isActor(object)) {
refactor(backend): `core/activitypub` (#11247) * eslint: `explicit-function-return-type` * eslint: `no-unnecessary-condition` * eslint: `eslint-disable-next-line` * eslint: `no-unused-vars` * eslint: `comma-dangle` * eslint: `import/order` * cleanup: unnecessary non-null assertion * cleanup: `IActivity`に`actor`は常に存在するようなので * cleanup: unnecessary `as` * cleanup: unnecessary `Promise.resolve` * cleanup * refactor: `String.prototype.match()`である必要がない部分をよりシンプルな書き方に変更 * refactor: よりよい型定義 * refactor: よりよい型定義 - `LdSignature`の`normalize`メソッドでの使われ方から、 - `data`引数の型定義を`any`から`JsonLdDocument`へ修正 - `getLoader`メソッドの返り値の型定義の一部を`any`から`RemoteDocument`へ修正 - `contextUrl`が不正な値(`null`)となっていたことが判明したため`undefined`へ修正 - `document`の型と合わせるために`CONTEXTS`の型定義の一部を`unknown`から`JsonLd`へ修正 - とりあえず`satisfies`を使用 - `document`の型と合わせるために`fetchDocument`メソッドの返り値の型定義の一部を`unknown`から`JsonLd`へ修正 - どうしようもなく`as`を使用 * refactor: 型ガードを使うことでnon-null assertionをやめた * refactor: non-null assertionをやめた `.filter()`で行っている型ガードなどの文脈から、より適しているだろうと思われる書き方に変更した。 * refactor: 型ガードを使うことで`as`をやめた * refactor: `as`をやめた * refactor: よりよい型定義 - `id`は`null`とのunionになっていたが、`null`を渡している場面はなかった - またおそらくこのメソッドは`IOrderedCollection`を返すため、そちらに合わせて`null`とのunionをやめた - `IOrderedCollection`とはまだ型に相違がある - `totalItems`をコメントや使われ方を元に`number`へ推論 * refactor: `for-of` -> `Array.prototype.map` * refactor: `delete`演算子を使わない形に
2023-07-13 03:48:34 +00:00
await this.apPersonService.updatePerson(actor.uri, resolver, object);
2022-09-17 18:27:08 +00:00
return 'ok: Person updated';
} else if (getApType(object) === 'Question') {
await this.apQuestionService.updateQuestion(object, resolver).catch(err => console.error(err));
2022-09-17 18:27:08 +00:00
return 'ok: Question updated';
2023-09-23 00:32:49 +00:00
} else if (getApType(object) === 'Note') {
await this.apNoteService.updateNote(object, resolver).catch(err => console.error(err));
return 'ok: Note updated';
2022-09-17 18:27:08 +00:00
} else {
return `skip: Unknown type: ${getApType(object)}`;
}
}
@bindThis
private async move(actor: MiRemoteUser, activity: IMove): Promise<string> {
// fetch the new and old accounts
const targetUri = getApHrefNullable(activity.target);
if (!targetUri) return 'skip: invalid activity target';
enhance: account migration (#10592) * copy block and mute then create follow and unfollow jobs * copy block and mute and update lists when detecting an account has moved * no need to care promise orders * refactor updating actor and target * automatically accept if a locked account had accepted an old account * fix exception format * prevent the old account from calling some endpoints * do not unfollow when moving * adjust following and follower counts * check movedToUri when receiving a follow request * skip if no need to adjust * Revert "disable account migration" This reverts commit 2321214c98591bcfe1385c1ab5bf0ff7b471ae1d. * fix translation specifier * fix checking alsoKnownAs and uri * fix updating account * fix refollowing locked account * decrease followersCount if followed by the old account * adjust following and followers counts when unfollowing * fix copying mutings * prohibit moved account from moving again * fix move service * allow app creation after moving * fix lint * remove unnecessary field * fix cache update * add e2e test * add e2e test of accepting the new account automatically * force follow if any error happens * remove unnecessary joins * use Array.map instead of for const of * ユーザーリストの移行は追加のみを行う * nanka iroiro * fix misskey-js? * :v: * 移行を行ったアカウントからのフォローリクエストの自動許可を調整 * newUriを外に出す * newUriを外に出す2 * clean up * fix newUri * prevent moving if the destination account has already moved * set alsoKnownAs via /i/update * fix database initialization * add return type * prohibit updating alsoKnownAs after moving * skip to add to alsoKnownAs if toUrl is known * skip adding to the list if it already has * use Acct.parse instead * rename error code * :art: * 制限を5から10に緩和 * movedTo(Uri), alsoKnownAsはユーザーidを返すように * test api res * fix * 元アカウントはミュートし続ける * :art: * unfollow * fix * getUserUriをUserEntityServiceに * ? * job! * :art: * instance => server * accountMovedShort, forbiddenBecauseYouAreMigrated * accountMovedShort * fix test * import, pin禁止 * 実績を凍結する * clean up * :v: * change message * ブロック, フォロー, ミュート, リストのインポートファイルの制限を32MiBに * Revert "ブロック, フォロー, ミュート, リストのインポートファイルの制限を32MiBに" This reverts commit 3bd7be35d8aa455cb01ae58f8172a71a50485db1. * validateAlsoKnownAs * 移行後2時間以内はインポート可能なファイルサイズを拡大 * clean up * どうせactorをupdatePersonで更新するならupdatePersonしか移行処理を発行しないことにする * handle error? * リモートからの移行処理の条件を是正 * log, port * fix * fix * enhance(dev): non-production環境でhttpサーバー間でもユーザー、ノートの連合が可能なように * refactor (use checkHttps) * MISSKEY_WEBFINGER_USE_HTTP * Environment Variable readme * NEVER USE IN PRODUCTION * fix punyHost * fix indent * fix * experimental --------- Co-authored-by: tamaina <tamaina@hotmail.co.jp> Co-authored-by: syuilo <Syuilotan@yahoo.co.jp>
2023-04-29 15:09:29 +00:00
return await this.apPersonService.updatePerson(actor.uri) ?? 'skip: nothing to do';
}
2022-09-17 18:27:08 +00:00
}