From 76487de5ed7d77aa1f3c4b9882530dfec7b7477f Mon Sep 17 00:00:00 2001
From: tamaina <tamaina@hotmail.co.jp>
Date: Sun, 10 Mar 2024 16:17:09 +0000
Subject: [PATCH] =?UTF-8?q?=E3=81=A8=E3=82=8A=E3=81=82=E3=81=88=E3=81=9Atr?=
 =?UTF-8?q?y=E3=81=A7=E5=9B=B2=E3=81=A3=E3=81=A6=E3=81=8A=E3=81=8F?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .../activitypub/models/ApPersonService.ts     | 32 +++++++++++--------
 1 file changed, 19 insertions(+), 13 deletions(-)

diff --git a/packages/backend/src/core/activitypub/models/ApPersonService.ts b/packages/backend/src/core/activitypub/models/ApPersonService.ts
index 814c4646b6..1b01b9e2a9 100644
--- a/packages/backend/src/core/activitypub/models/ApPersonService.ts
+++ b/packages/backend/src/core/activitypub/models/ApPersonService.ts
@@ -551,23 +551,29 @@ export class ApPersonService implements OnModuleInit {
 		// Update user
 		await this.usersRepository.update(exist.id, updates);
 
-		const publicKeys = new Map<string, IKey>();
-		if (person.publicKey) {
-			(person.additionalPublicKeys ?? []).forEach(key => publicKeys.set(key.id, key));
-			publicKeys.set(person.publicKey.id, person.publicKey);
+		try {
+			// Deleteアクティビティ受信時にもここが走ってsaveがuserforeign key制約エラーを吐くことがある
+			// とりあえずtry-catchで囲っておく
+			const publicKeys = new Map<string, IKey>();
+			if (person.publicKey) {
+				(person.additionalPublicKeys ?? []).forEach(key => publicKeys.set(key.id, key));
+				publicKeys.set(person.publicKey.id, person.publicKey);
 
-			await this.userPublickeysRepository.save(Array.from(publicKeys.values(), key => ({
-				keyId: key.id,
+				await this.userPublickeysRepository.save(Array.from(publicKeys.values(), key => ({
+					keyId: key.id,
+					userId: exist.id,
+					keyPem: key.publicKeyPem,
+				})));
+			}
+
+			this.userPublickeysRepository.delete({
+				keyId: Not(In(Array.from(publicKeys.keys()))),
 				userId: exist.id,
-				keyPem: key.publicKeyPem,
-			})));
+			});
+		} catch (err) {
+			this.logger.error('something happened while updating remote user public keys:', { err });
 		}
 
-		this.userPublickeysRepository.delete({
-			keyId: Not(In(Array.from(publicKeys.keys()))),
-			userId: exist.id,
-		});
-
 		let _description: string | null = null;
 
 		if (person._misskey_summary) {