Compare commits

...

54 commits

Author SHA1 Message Date
598b88b142 Merge pull request 'Replace notes(userId) index with (userId, id)' (#28) from sugar/forkey:replace-notes-user-id-index-with-user-id-id into main
Reviewed-on: woem.men/forkey#28
Reviewed-by: leah <leah@noreply.woem.men>
2025-02-23 13:05:54 +00:00
e90e9e016f Merge pull request 'implement mastodon oauth authorization' (#22) from sugar/forkey:implement-mastodon-oauth into main
Reviewed-on: woem.men/forkey#22
Reviewed-by: leah <leah@noreply.woem.men>
2025-02-08 22:01:20 +00:00
125bf6fe93 implement mastodon push permission
currently doesn't do anything, but it's necessary for masto-fe to be
able to sign in
2025-02-07 21:53:22 +01:00
32fc7644fc add support for form bodies for mastodon apis
this separates registration of mastodon endpoints to another register
scope so that form body parsing wouldn't affect misskey apis
2025-02-07 21:53:22 +01:00
04c1c0e1e6 implement mastodon oauth authorization 2025-02-07 21:42:36 +01:00
cfba325ae7 Merge pull request 'frontend performance improvements' (#59) from sugar/forkey:frontend-performance-improvements into main
Reviewed-on: woem.men/forkey#59
Reviewed-by: leah <leah@noreply.woem.men>
2025-02-07 18:36:39 +00:00
ed302618f2 Merge pull request 'Split catspeak and isCat & Accessability' (#48) from feature/speakAsCat into main
Reviewed-on: woem.men/forkey#48
2025-02-05 04:22:02 +00:00
12a9dab275 fix tests? 2025-02-04 14:39:49 +01:00
55a2b82330 Merge branch 'main' into feature/speakAsCat 2025-02-04 13:33:11 +00:00
0ef9fb12c4 Merge pull request 'Merge upstream 2025-01-17' (#40) from sugar/forkey:merge-upstream-2025-01-17 into main
Reviewed-on: woem.men/forkey#40
2025-02-03 16:05:49 +00:00
0ceb07314b Merge branch 'main' into merge-upstream-2025-01-17 2025-02-03 15:53:27 +00:00
f0de9000a0 fix mix of tabs and spaces 2025-02-03 16:04:12 +01:00
513b8b2bba Merge pull request 'Line numbers on code blocks' (#46) from feature/line-numbers-on-code-blocks into main
Reviewed-on: woem.men/forkey#46
2025-02-03 13:12:18 +00:00
7e21b10a4f Merge branch 'main' into feature/line-numbers-on-code-blocks 2025-02-03 12:34:38 +00:00
83c1dc4105 Merge branch 'main' into merge-upstream-2025-01-17 2025-02-03 12:29:05 +00:00
71606c5507 avoid computing tooltip position every frame
this fixes an issue causing misskey to constantly recompute tooltip
position when any kind of chart is being displayed (such as the one
on user profile page, or any page for unauthenticated users)
2025-02-02 17:33:33 +01:00
8165088886 only run parallax effect when scrolling user profile
running animation handler every frame is slow
2025-02-02 16:58:14 +01:00
f4bda8582f Merge pull request 'avoid cloning entire repo for actions/checkout' (#47) from sugar/forkey:avoid-cloning-entire-repo-in-actions-checkout into main
Reviewed-on: woem.men/forkey#47
2025-01-19 20:59:34 +00:00
140daecf2f split speak as cat and is cat. Also add option for other people to disable it so they dont have to see cat speak 2025-01-19 19:43:39 +01:00
41a9904932 avoid cloning entire repo for actions/checkout
`fetch-depth: 0` is saying to fetch all commits, which we don't really
need test for testing a single commit
2025-01-19 19:43:34 +01:00
9eded797d6 add line numbers on code blocks 2025-01-19 17:34:43 +01:00
9e4fd869d2 Merge branch 'main' into merge-upstream-2025-01-17 2025-01-19 09:31:36 +01:00
6b7e6bedb3 Merge branch 'main' into merge-upstream-2025-01-17 2025-01-19 01:08:29 +01:00
d35b2dd0bc Revert "fix(frontend/mobile): モバイルでkawaiiモードが適用されない問題を修正 (MisskeyIO#878)"
This reverts commit 8bd7884873.
2025-01-17 16:40:25 +01:00
2ac89cd654 Merge remote-tracking branch 'misskeyio/io' into merge-upstream-2025-01-17 2025-01-17 16:35:12 +01:00
sugar🍬🍭🏳️‍⚧️
15414e4ce5
perf: dynamically load audio visualizer (MisskeyIO#912)
audio visualizer weights 475 kB by itself, and audio files are
relatively rare on timelines, so it makes sense to load it only when
it's necessary
2025-01-17 23:21:08 +09:00
あわわわとーにゅ
d423d9bb44
fix(MisskeyIO#907): サブスクライブコマンドは必要だった (MisskeyIO#910) 2025-01-17 20:47:10 +09:00
あわわわとーにゅ
428ff56abe
Bump up version to 2024.5.0-io.7c (MisskeyIO#908) 2025-01-17 18:35:28 +09:00
あわわわとーにゅ
c4fafbdca7
perf(stream): 必要のない既読処理のメッセージが発生しないように (MisskeyIO#907) 2025-01-17 18:35:08 +09:00
あわわわとーにゅ
8821e3e81b
spec(role/ScheduledNote): ロールで予約投稿の個数・予約の最大日数を制御できるように (MisskeyIO#906) 2025-01-17 17:08:13 +09:00
あわわわとーにゅ
f0f86f1121
spec(backend/queue/ScheduledNote): 予約時間が過ぎる前にチェックするように (MisskeyIO#905) 2025-01-17 16:50:01 +09:00
あわわわとーにゅ
655ed957bc
enhance(ux/frontend/MkPostForm): 予約投稿の時間を再度設定する時、以前設定した時間が表示されるように (MisskeyIO#904) 2025-01-17 16:49:42 +09:00
あわわわとーにゅ
71c2921b9d
fix(backend/SigninApiService): ログインのレートリミット時、意図したものと違うエラーメッセージが表示される可能性がある問題を修正 (MisskeyIO#903) 2025-01-17 16:49:16 +09:00
あわわわとーにゅ
f60d9da614
chore(frontend): 通報のカテゴリの調整・投稿フォームのガイドラインへの導線に利用規約も追加 (MisskeyIO#902) 2025-01-17 16:48:54 +09:00
あわわわとーにゅ
a075b6aeef
Bump up version to 2024.5.0-io.7b (MisskeyIO#899) 2025-01-17 08:47:46 +09:00
あわわわとーにゅ
fc31c0e219
fix(frontend/MkDraftsDialog): 🎨 (MisskeyIO#898) 2025-01-17 08:43:17 +09:00
あわわわとーにゅ
f69e489442
Bump up version to 2024.5.0-io.7a (MisskeyIO#896) 2025-01-17 04:54:29 +09:00
あわわわとーにゅ
bcb85f2237
fix(backend/object-storage): disable data integrity protections (MisskeyIO#895)
Cloudflare R2 does not support 'x-amz-checksum-*'
2025-01-17 04:50:58 +09:00
あわわわとーにゅ
86209cf4b3
Bump up version to 2024.5.0-io.7 (MisskeyIO#893) 2025-01-16 23:29:14 +09:00
あわわわとーにゅ
6993e5b7fd
perf(frontend/css): MkNote 及び MkNotification に content-visibility を適用 (MisskeyIO#892) 2025-01-16 23:05:02 +09:00
あわわわとーにゅ
cbe80fdd26
feat(note): 予約投稿 (MisskeyIO#890) 2025-01-16 22:35:27 +09:00
あわわわとーにゅ
509f385402
update deps (MisskeyIO#891) 2025-01-16 19:46:20 +09:00
あわわわとーにゅ
68c3eb5b5d
update deps (MisskeyIO#889)
- メンテナンスされないredis-lockを自前実装に変更
- 既にロックされている場合のリトライ間隔を調整
2025-01-15 03:24:33 +09:00
あわわわとーにゅ
5f6cbe048a
Bump up version to 2024.5.0-io.6a (MisskeyIO#888) 2025-01-14 03:28:47 +09:00
あわわわとーにゅ
9792ea0223
update deps (MisskeyIO#887)
(cherry picked from commit f7da2bad6f0b25652ded11e6a9f86efc40872200)
(cherry picked from commit d60c307c4e4c3eaba2a40b46ba41c4d684d5d370)

Co-authored-by: おさむのひと <46447427+samunohito@users.noreply.github.com>
Co-authored-by: かっこかり <67428053+kakkokari-gtyih@users.noreply.github.com>
2025-01-14 02:19:05 +09:00
あわわわとーにゅ
cf1952ac0d
spec(MisskeyIO#884): 送信ボタンをアイコンのみの表示にするしきい値を変更 2 (MisskeyIO#886) 2025-01-14 01:09:38 +09:00
あわわわとーにゅ
d4baf040cc
spec(MisskeyIO#884): 送信ボタンをアイコンのみの表示にするしきい値を変更 (MisskeyIO#885) 2025-01-13 09:10:28 +09:00
まっちゃてぃー。
c88478f31b
fix(frontend): 一定の条件でノート送信ボタンが意図しない見た目になる問題を修正 (MisskeyIO#884)
Co-authored-by: あわわわとーにゅ <17376330+u1-liquid@users.noreply.github.com>
2025-01-13 08:19:32 +09:00
あわわわとーにゅ
f280ce2a39
Bump up version to 2024.5.0-io.6 (MisskeyIO#882) 2025-01-12 18:36:36 +09:00
あわわわとーにゅ
31d57f270c
feat(frontend/draft): 下書き機能の改良・強化 (MisskeyIO#881) 2025-01-12 18:36:16 +09:00
あわわわとーにゅ
8a0b98aa26
Sync charts one-at-a-time to reduce database contention and timeouts (MisskeyIO#880)
(cherry picked from https://activitypub.software/TransFem-org/Sharkey/-/merge_requests/830)

Co-authored-by: Hazelnoot <acomputerdog@gmail.com>
2025-01-10 15:16:28 +09:00
あわわわとーにゅ
535a6bc756
spec(notes/create): 投稿されたnoteを返さないオプションを追加 (MisskeyIO#879) 2025-01-10 14:54:32 +09:00
あわわわとーにゅ
8bd7884873
fix(frontend/mobile): モバイルでkawaiiモードが適用されない問題を修正 (MisskeyIO#878) 2025-01-10 14:17:14 +09:00
あわわわとーにゅ
0d24c8843c
fix(MisskeyIO#866): ユーザーメニューからロールの割り当て時メモを入力しないとキャンセル扱いされる問題を修正 (MisskeyIO#877) 2025-01-09 10:21:50 +09:00
143 changed files with 5319 additions and 2773 deletions

View file

@ -17,7 +17,6 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: true
- name: Install pnpm

View file

@ -21,7 +21,6 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: true
- name: Check version
run: |

View file

@ -24,7 +24,6 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: true
- uses: pnpm/action-setup@v4.0.0
with:
@ -49,7 +48,6 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: true
- uses: pnpm/action-setup@v4.0.0
with:
@ -73,7 +71,6 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: true
- uses: pnpm/action-setup@v4.0.0
with:

View file

@ -44,7 +44,6 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: true
- name: Install pnpm
uses: pnpm/action-setup@v4.0.0
@ -96,7 +95,6 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: true
- name: Install pnpm
uses: pnpm/action-setup@v4.0.0

View file

@ -32,7 +32,6 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: true
- name: Install pnpm
uses: pnpm/action-setup@v4.0.0

View file

@ -27,7 +27,6 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: true
- name: Install pnpm

View file

@ -20,7 +20,6 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: true
- name: Install pnpm
uses: pnpm/action-setup@v4.0.0

View file

@ -21,7 +21,6 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: true
- name: Install pnpm
uses: pnpm/action-setup@v4.0.0

View file

@ -175,6 +175,8 @@ flagAsBot: "Mark this account as a bot"
flagAsBotDescription: "Enable this option if this account is controlled by a program. If enabled, it will act as a flag for other developers to prevent endless interaction chains with other bots and adjust Misskey's internal systems to treat this account as a bot."
flagAsCat: "Mark this account as a cat"
flagAsCatDescription: "Enable this option to mark this account as a cat."
flagSpeakAsCat: "Speak as a cat"
flagSpeakAsCatDescription: "Your posts will get nyanified when in cat mode. If this isn't working, then please check that you dont have 'Disable cat speak' on under General/Note Display"
flagShowTimelineReplies: "Show replies in timeline"
flagShowTimelineRepliesDescription: "Shows replies of users to notes of other users in the timeline if turned on."
autoAcceptFollowed: "Automatically approve follow requests from users you're following"
@ -762,6 +764,7 @@ noCrawleDescription: "Ask search engines to not index your profile page, notes,
lockedAccountInfo: "Unless you set your note visiblity to \"Followers only\", your notes will be visible to anyone, even if you require followers to be manually approved."
alwaysMarkSensitive: "Mark as sensitive by default"
loadRawImages: "Load original images instead of showing thumbnails"
disableCatSpeak: "Disable cat speak"
disableShowingAnimatedImages: "Don't play animated images"
highlightSensitiveMedia: "Highlight sensitive media"
verificationEmailSent: "A verification email has been sent. Please follow the included link to complete verification."
@ -1333,6 +1336,14 @@ consentAll: "Allow All Items"
consentSelected: "Allow Selected Items"
emailAddressLogin: "Login with email address"
usernameLogin: "Login with username"
autoloadDrafts: "Automatically load drafts when opening the posting form"
drafts: "Drafts"
unsent: "Unsent"
schedule: "Schedule"
scheduled: "Scheduled"
unschedule: "Unschedule"
setScheduledTime: "Set scheduled time"
willBePostedAt: "Note will be posted at {x}"
_bubbleGame:
howToPlay: "How to play"
@ -1373,8 +1384,8 @@ _abuseReportCategory:
otherBreach_description: "Other actions that violate the terms but do not fall under specific categories"
violationRights: "Rights Infringement or Impersonation (Reported by Rights Holder)"
violationRights_description: "Posts infringing the rights (such as copyright or trademark) of the rights holder or impersonation"
violationRightsOther: "Rights Infringement or Impersonation (Reported by Third Party)"
violationRightsOther_description: "Posts infringing the rights (such as copyright or trademark) of others or impersonation\nIf reported by a third party, cases outside the scope of non-complaint offenses as defined by law may not be addressed"
violationRightsOther: "Rights Infringement (Reported by Third Party)"
violationRightsOther_description: "Posts infringing the rights (such as copyright or trademark) of others\nIf reported by a third party, cases outside the scope of non-complaint offenses as defined by law may not be addressed"
notLike: "Dislike This Person"
notLike_description: "Users or posts that you find unpleasant for personal reasons"
other: "Other"
@ -1801,6 +1812,9 @@ _role:
gtlAvailable: "Can view the global timeline"
ltlAvailable: "Can view the local timeline"
canPublicNote: "Can send public notes"
canScheduleNote: "Can schedule notes"
scheduleNoteLimit: "Maximum number of scheduled notes"
scheduleNoteMaxDays: "Maximum number of days that note can be scheduled"
canInitiateConversation: "Can mention, reply or quote"
canCreateContent: "Can create contents"
canUpdateContent: "Can edit contents"
@ -2229,6 +2243,7 @@ _permissions:
"read:clip-favorite": "View favorited clips"
"read:federation": "Get federation data"
"write:report-abuse": "Report violation"
"write:push-notification": "Receive push notifications"
_auth:
shareAccessTitle: "Granting application permissions"
shareAccess: "Would you like to authorize \"{name}\" to access this account?"
@ -2337,6 +2352,8 @@ _postForm:
d: "What do you want to say?"
e: "Start writing..."
f: "Waiting for you to write..."
policyScheduleNoteMaxDaysExceeded: "The maximum number of days you can schedule notes for with your current support plan is {max}.\nYou can upgrade your plan [here](https://go.misskey.io/donate)."
tosAndGuidelinesInfo: "Before posting, please read the [Terms of Service]({tosUrl}) and [NSFW Guidelines](https://go.misskey.io/media-guideline)."
_profile:
name: "Name"
username: "Username"
@ -2361,7 +2378,7 @@ _profile:
sectionName: "Section name"
sectionNameNoneDescription: "Do not display the section name"
sectionNameNone: "Section without name"
policyDisplayLimitExceeded: "The number of items displayed exceeds the current support plan's limit ({max}). This item will not be displayed. You can upgrade your plan [here](https://go.misskey.io/donate)."
policyDisplayLimitExceeded: "The number of items displayed exceeds the current support plan's limit ({max}). This item will not be displayed.\nYou can upgrade your plan [here](https://go.misskey.io/donate)."
_exportOrImport:
allNotes: "All notes"
favoritedNotes: "Favorite notes"
@ -2494,6 +2511,9 @@ _notification:
roleAssigned: "Role given"
emptyPushNotificationMessage: "Push notifications have been updated"
achievementEarned: "Achievement unlocked"
noteScheduled: "Note has been scheduled"
scheduledNotePosted: "Scheduled note has been posted"
scheduledNoteError: "Scheduled note has problem with posting"
testNotification: "Test notification"
checkNotificationBehavior: "Check notification appearance"
sendTestNotification: "Send test notification"
@ -2517,6 +2537,9 @@ _notification:
followRequestAccepted: "Accepted follow requests"
roleAssigned: "Role given"
achievementEarned: "Achievement unlocked"
noteScheduled: "Note scheduled"
scheduledNotePosted: "Scheduled note posted"
scheduledNoteError: "Problem with scheduled note"
app: "Notifications from linked apps"
_actions:
followBack: "followed you back"

98
locales/index.d.ts vendored
View file

@ -724,6 +724,14 @@ export interface Locale extends ILocale {
*
*/
"flagAsCatDescription": string;
/**
*
*/
"flagSpeakAsCat": string;
/**
* 稿
*/
"flagSpeakAsCatDescription": string;
/**
*
*/
@ -3064,6 +3072,10 @@ export interface Locale extends ILocale {
*
*/
"loadRawImages": string;
/**
*
*/
"disableCatSpeak": string;
/**
*
*/
@ -5386,6 +5398,38 @@ export interface Locale extends ILocale {
*
*/
"usernameLogin": string;
/**
* 稿
*/
"autoloadDrafts": string;
/**
*
*/
"drafts": string;
/**
*
*/
"unsent": string;
/**
*
*/
"schedule": string;
/**
*
*/
"scheduled": string;
/**
*
*/
"unschedule": string;
/**
*
*/
"setScheduledTime": string;
/**
* {x}稿
*/
"willBePostedAt": ParameterizedString<"x">;
"_bubbleGame": {
/**
*
@ -5514,11 +5558,11 @@ export interface Locale extends ILocale {
*/
"violationRights_description": string;
/**
*
*
*/
"violationRightsOther": string;
/**
* 稿
*
*
*/
"violationRightsOther_description": string;
@ -6843,7 +6887,7 @@ export interface Locale extends ILocale {
};
"_tutorialCompleted": {
/**
* Misskey初心者講座
* Forkey初心者講座
*/
"title": string;
/**
@ -7039,6 +7083,18 @@ export interface Locale extends ILocale {
* 稿
*/
"canPublicNote": string;
/**
* 稿
*/
"canScheduleNote": string;
/**
* 稿
*/
"scheduleNoteLimit": string;
/**
* 稿
*/
"scheduleNoteMaxDays": string;
/**
*
*/
@ -9110,9 +9166,14 @@ export interface Locale extends ILocale {
"f": string;
};
/**
* [NSFWガイドライン]({nsfwGuideUrl})
* {max}
* [](https://go.misskey.io/donate)からプランをアップグレードできます。
*/
"guidelineInfo": ParameterizedString<"nsfwGuideUrl">;
"policyScheduleNoteMaxDaysExceeded": ParameterizedString<"max">;
/**
* 稿[]({tosUrl})[NSFWガイドライン](https://go.misskey.io/media-guideline)を必ずお読みください。
*/
"tosAndGuidelinesInfo": ParameterizedString<"tosUrl">;
};
"_profile": {
/**
@ -9208,7 +9269,8 @@ export interface Locale extends ILocale {
*/
"sectionNameNone": string;
/**
* ({max})[](https://go.misskey.io/donate)からプランをアップグレードできます。
* ({max})
* [](https://go.misskey.io/donate)からプランをアップグレードできます。
*/
"policyDisplayLimitExceeded": ParameterizedString<"max">;
};
@ -9719,6 +9781,18 @@ export interface Locale extends ILocale {
*
*/
"achievementEarned": string;
/**
*
*/
"noteScheduled": string;
/**
* 稿
*/
"scheduledNotePosted": string;
/**
* 稿
*/
"scheduledNoteError": string;
/**
*
*/
@ -9808,6 +9882,18 @@ export interface Locale extends ILocale {
*
*/
"achievementEarned": string;
/**
*
*/
"noteScheduled": string;
/**
* 稿
*/
"scheduledNotePosted": string;
/**
* 稿
*/
"scheduledNoteError": string;
/**
*
*/

View file

@ -72,7 +72,7 @@ export function build() {
.reduce((a, [k, v]) => (a[k] = (() => {
const [lang] = k.split('-');
switch (k) {
case 'ja-JP': return v;
case 'ja-JP': return merge(locales['en-US'], v);
case 'ja-KS':
case 'en-US': return merge(locales['ja-JP'], v);
default: return merge(

View file

@ -177,6 +177,8 @@ flagAsBot: "Botとして設定"
flagAsBotDescription: "このアカウントがプログラムによって運用される場合は、このフラグをオンにします。オンにすると、反応の連鎖を防ぐためのフラグとして他の開発者に役立ったり、Misskeyのシステム上での扱いがBotに合ったものになります。"
flagAsCat: "にゃああああああああああああああ!!!!!!!!!!!!"
flagAsCatDescription: "にゃにゃにゃ??"
flagSpeakAsCat: "猫語で話す"
flagSpeakAsCatDescription: "有効にすると、あなたの投稿の 「な」を「にゃ」にします。"
flagShowTimelineReplies: "タイムラインにノートへの返信を表示する"
flagShowTimelineRepliesDescription: "オンにすると、タイムラインにユーザーのノート以外にもそのユーザーの他のノートへの返信を表示します。"
autoAcceptFollowed: "フォロー中ユーザーからのフォロリクを自動承認"
@ -762,6 +764,7 @@ noCrawleDescription: "外部の検索エンジンにあなたのユーザーペ
lockedAccountInfo: "フォローを承認制にしても、ノートの公開範囲を「フォロワー」にしない限り、誰でもあなたのノートを見ることができます。"
alwaysMarkSensitive: "デフォルトでメディアをセンシティブ設定にする"
loadRawImages: "添付画像のサムネイルをオリジナル画質にする"
disableCatSpeak: "猫の話し方を無効にする"
disableShowingAnimatedImages: "アニメーション画像を再生しない"
highlightSensitiveMedia: "メディアがセンシティブであることを分かりやすく表示"
verificationEmailSent: "確認のメールを送信しました。メールに記載されたリンクにアクセスして、設定を完了してください。"
@ -1340,6 +1343,14 @@ consentAll: "全て許可"
consentSelected: "選択した項目のみ許可"
emailAddressLogin: "メールアドレスでログイン"
usernameLogin: "ユーザー名でログイン"
autoloadDrafts: "投稿フォームを開いたときに下書きを自動で読み込む"
drafts: "下書き"
unsent: "未送信"
schedule: "予約"
scheduled: "予約済み"
unschedule: "予約を解除"
setScheduledTime: "予約日時を設定"
willBePostedAt: "{x}に投稿されます"
_bubbleGame:
howToPlay: "遊び方"
@ -1376,8 +1387,8 @@ _abuseReportCategory:
otherBreach_description: "明確に分類されないその他の規約違反行為"
violationRights: "権利侵害やなりすまし(侵害を受けた権利者本人によるご申告)"
violationRights_description: "権利者本人の著作権、商標権、またはその他の権利を侵害する投稿及びなりすまし行為"
violationRightsOther: "権利侵害やなりすまし(第三者による通報)"
violationRightsOther_description: "他人の著作権、商標権、またはその他の権利を侵害する投稿及びなりすまし行為\n第三者による通報の場合、法律で定められた非親告罪の範囲外のケースには対応できないことがあります"
violationRightsOther: "権利侵害(第三者による通報)"
violationRightsOther_description: "他人の著作権、商標権、またはその他の権利を侵害する行為\n第三者による通報の場合、法律で定められた非親告罪の範囲外のケースには対応できないことがあります"
notLike: "この人が気に入らない"
notLike_description: "個人的な理由で不快と感じるユーザーや投稿"
other: "その他"
@ -1813,6 +1824,9 @@ _role:
gtlAvailable: "グローバルタイムラインの閲覧"
ltlAvailable: "ローカルタイムラインの閲覧"
canPublicNote: "パブリック投稿の許可"
canScheduleNote: "予約投稿の許可"
scheduleNoteLimit: "予約投稿の最大数"
scheduleNoteMaxDays: "予約投稿の最大日数"
canInitiateConversation: "メンション、リプライ、引用の許可"
canCreateContent: "コンテンツの作成"
canUpdateContent: "コンテンツの編集"
@ -2390,7 +2404,8 @@ _postForm:
d: "言いたいことは?"
e: "ここに書いてください"
f: "あなたが書くのを待っています..."
guidelineInfo: "[NSFWガイドライン]({nsfwGuideUrl})を必ずお読みになってからご利用ください。"
policyScheduleNoteMaxDaysExceeded: "現在の支援プランで予約できる日数の上限は{max}日です。\n[ここ](https://go.misskey.io/donate)からプランをアップグレードできます。"
tosAndGuidelinesInfo: "投稿する前に、[利用規約]({tosUrl})と[NSFWガイドライン](https://go.misskey.io/media-guideline)を必ずお読みください。"
_profile:
name: "名前"
@ -2416,7 +2431,7 @@ _profile:
sectionName: "セクション名"
sectionNameNoneDescription: "セクション名を表示しないようにする"
sectionNameNone: "名前が表示されないセクション"
policyDisplayLimitExceeded: "現在の支援プランの表示上限({max}個)を超えているため、この項目は表示されません。[ここ](https://go.misskey.io/donate)からプランをアップグレードできます。"
policyDisplayLimitExceeded: "現在の支援プランの表示上限({max}個)を超えているため、この項目は表示されません。\n[ここ](https://go.misskey.io/donate)からプランをアップグレードできます。"
_exportOrImport:
allNotes: "全てのノート"
@ -2558,6 +2573,9 @@ _notification:
roleAssigned: "ロールが付与されました"
emptyPushNotificationMessage: "プッシュ通知の更新をしました"
achievementEarned: "実績を獲得"
noteScheduled: "ノートが予約されました"
scheduledNotePosted: "予約済みのノートが投稿されました"
scheduledNoteError: "予約済みのノートを投稿できませんでした"
testNotification: "通知テスト"
checkNotificationBehavior: "通知の表示を確かめる"
sendTestNotification: "テスト通知を送信する"
@ -2582,6 +2600,9 @@ _notification:
followRequestAccepted: "フォローが受理された"
roleAssigned: "ロールが付与された"
achievementEarned: "実績の獲得"
noteScheduled: "ノートが予約された"
scheduledNotePosted: "予約済みのノートが投稿された"
scheduledNoteError: "予約済みのノートが投稿できなかった"
app: "連携アプリからの通知"
_actions:

View file

@ -1314,6 +1314,14 @@ consentAll: "모두 허용"
consentSelected: "선택한 항목만 허용"
emailAddressLogin: "이메일 주소로 로그인"
usernameLogin: "사용자명으로 로그인"
autoloadDrafts: "글 작성 시 자동으로 임시 저장된 글 불러오기"
drafts: "임시 저장"
unsent: "미전송"
schedule: "예약"
scheduled: "예약됨"
unschedule: "예약 취소"
setScheduledTime: "예약 시간 설정"
willBePostedAt: "{x}에 게시됩니다"
_bubbleGame:
howToPlay: "설명"
@ -1354,8 +1362,8 @@ _abuseReportCategory:
otherBreach_description: "명확하게 분류되지 않는 기타 규약 위반 행위"
violationRights: "권리 침해 또는 사칭 (권리자 본인에 의한 신고)"
violationRights_description: "권리자 본인의 저작권, 상표권 또는 기타 권리를 침해하는 게시물 및 사칭 행위"
violationRightsOther: "권리 침해 또는 사칭 (제3자에 의한 신고)"
violationRightsOther_description: "타인의 저작권, 상표권 또는 기타 권리를 침해하는 게시물 및 사칭 행위\n제3자에 의한 신고의 경우, 법으로 정해진 비친고죄 범위 외의 사례에는 대응할 수 없습니다"
violationRightsOther: "권리 침해 (제3자에 의한 신고)"
violationRightsOther_description: "타인의 저작권, 상표권 또는 기타 권리를 침해하는 행위\n제3자에 의한 신고의 경우, 법으로 정해진 비친고죄 범위 외의 사례에는 대응할 수 없습니다"
notLike: "이 사람이 마음에 들지 않음"
notLike_description: "개인적인 이유로 불쾌감을 느끼는 사용자나 게시물"
other: "기타"
@ -1782,6 +1790,9 @@ _role:
gtlAvailable: "글로벌 타임라인 보이기"
ltlAvailable: "로컬 타임라인 보이기"
canPublicNote: "공개 노트 허용"
canScheduleNote: "노트 예약 허용"
scheduleNoteLimit: "노트 예약 한도"
scheduleNoteMaxDays: "노트 예약 최대 일수"
mentionMax: "노트에 넣을 수 있는 멘션 수"
canCreateContent: "컨텐츠 생성 허용"
canUpdateContent: "컨텐츠 수정 허용"
@ -2301,6 +2312,8 @@ _postForm:
d: "말하고 싶은 게 있나요?"
e: "여기에 적어 주세요"
f: "글 쓰기를 기다려요…"
policyScheduleNoteMaxDaysExceeded: "현재 지원 플랜의 예약 가능한 최대 일수는 {max}일입니다.\n[여기](https://go.misskey.io/donate)에서 플랜을 업그레이드할 수 있습니다."
tosAndGuidelinesInfo: "노트를 게시하기 전에 [이용약관]({tosUrl})과 [NSFW 가이드라인](https://go.misskey.io/media-guideline)을 반드시 읽어 주세요."
_profile:
name: "이름"
username: "사용자 이름"
@ -2325,7 +2338,7 @@ _profile:
sectionName: "섹션 이름"
sectionNameNoneDescription: "섹션 이름이 표시되지 않도록 합니다"
sectionNameNone: "이름이 표시되지 않는 섹션"
policyDisplayLimitExceeded: "현재 지원 플랜의 표시 제한({max}개)을 초과하였기 때문에 이 항목은 표시되지 않습니다. [여기](https://go.misskey.io/donate)에서 플랜을 업그레이드할 수 있습니다."
policyDisplayLimitExceeded: "현재 지원 플랜의 표시 제한({max}개)을 초과하였기 때문에 이 항목은 표시되지 않습니다.\n[여기](https://go.misskey.io/donate)에서 플랜을 업그레이드할 수 있습니다."
_exportOrImport:
allNotes: "모든 노트"
favoritedNotes: "즐겨찾기한 노트"
@ -2454,9 +2467,12 @@ _notification:
pollEnded: "투표 결과가 발표되었습니다"
newNote: "새 게시물"
unreadAntennaNote: "안테나 {name}"
roleAssigned: "역할이 부여 되었습니다."
roleAssigned: "역할이 부여 되었습니다"
emptyPushNotificationMessage: "푸시 알림이 갱신되었습니다"
achievementEarned: "도전 과제를 달성했습니다"
noteScheduled: "노트가 예약되었습니다"
scheduledNotePosted: "예약된 노트가 게시되었습니다"
scheduledNoteError: "예약된 노트를 게시하지 못했습니다"
testNotification: "알림 테스트"
checkNotificationBehavior: "알림 표시를 체크하기"
sendTestNotification: "테스트 알림 보내기"
@ -2480,6 +2496,9 @@ _notification:
followRequestAccepted: "팔로우 요청이 승인되었을 때"
roleAssigned: "역할이 부여 됨"
achievementEarned: "도전 과제 획득"
noteScheduled: "노트가 예약됨"
scheduledNotePosted: "예약된 노트가 게시됨"
scheduledNoteError: "예약된 노트를 게시하지 못함"
app: "연동된 앱을 통한 알림"
_actions:
followBack: "팔로우"

View file

@ -1,12 +1,12 @@
{
"name": "forkey",
"version": "2024.5.0-io.5e",
"version": "2024.5.0-io.7c",
"codename": "nasubi",
"repository": {
"type": "git",
"url": "https://git.woem.men/woem.men/forkey.git"
},
"packageManager": "pnpm@9.15.0",
"packageManager": "pnpm@9.15.4",
"workspaces": [
"packages/frontend",
"packages/backend",
@ -56,26 +56,26 @@
"jpeg-js": "0.4.4",
"lodash": "4.17.21",
"sharp": "0.33.5",
"tough-cookie": "5.0.0",
"web-streams-polyfill": "4.0.0"
"tough-cookie": "5.1.0",
"web-streams-polyfill": "4.1.0"
},
"dependencies": {
"cssnano": "7.0.6",
"execa": "9.5.2",
"js-yaml": "4.1.0",
"postcss": "8.4.49",
"postcss": "8.5.1",
"terser": "5.37.0",
"typescript": "5.7.2"
"typescript": "5.7.3"
},
"devDependencies": {
"@types/node": "22.10.2",
"@types/node": "22.10.7",
"@typescript-eslint/eslint-plugin": "7.10.0",
"@typescript-eslint/parser": "7.10.0",
"cross-env": "7.0.3",
"cypress": "13.17.0",
"eslint": "8.57.1",
"ncp": "2.0.0",
"start-server-and-test": "2.0.9"
"start-server-and-test": "2.0.10"
},
"optionalDependencies": {
"@tensorflow/tfjs-core": "4.22.0"

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

View file

@ -0,0 +1,12 @@
export class SpeakAsCat1696386694000 {
name = "SpeakAsCat1696386694000";
async up(queryRunner) {
await queryRunner.query(`ALTER TABLE "user" ADD "speakAsCat" boolean NOT NULL DEFAULT true`);
await queryRunner.query(`COMMENT ON COLUMN "user"."speakAsCat" IS 'Whether to speak as a cat if chosen.'`);
}
async down(queryRunner) {
await queryRunner.query(`ALTER TABLE "user" DROP COLUMN "speakAsCat"`);
}
}

View file

@ -0,0 +1,18 @@
export class MastodonOauth1736599563231 {
name = 'MastodonOauth1736599563231'
async up(queryRunner) {
await queryRunner.query(`ALTER TABLE "app" ADD "website" character varying(128)`);
await queryRunner.query(`COMMENT ON COLUMN "app"."website" IS 'Application website.'`);
await queryRunner.query(`ALTER TABLE "app" ADD "mastodonScopes" character varying(64) array`);
await queryRunner.query(`COMMENT ON COLUMN "app"."mastodonScopes" IS 'Mastodon app scopes, only set for apps created with Mastodon API.'`);
await queryRunner.query(`ALTER TABLE "app" ADD "redirectUris" character varying(512) array DEFAULT '{}' NOT NULL`);
await queryRunner.query(`COMMENT ON COLUMN "app"."redirectUris" IS 'Redirect URIs.'`);
}
async down(queryRunner) {
await queryRunner.query(`ALTER TABLE "app" DROP COLUMN "website"`);
await queryRunner.query(`ALTER TABLE "app" DROP COLUMN "mastodonScopes"`);
await queryRunner.query(`ALTER TABLE "app" DROP COLUMN "redirectUris"`);
}
}

View file

@ -0,0 +1,21 @@
export class ScheduledNote1736923279563 {
name = 'ScheduledNote1736923279563'
async up(queryRunner) {
await queryRunner.query(`CREATE TABLE "note_scheduled" ("id" character varying(32) NOT NULL, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "scheduledAt" TIMESTAMP WITH TIME ZONE, "reason" character varying(256), "userId" character varying(32) NOT NULL, "draft" jsonb NOT NULL, CONSTRAINT "PK_14ca8fa67f70dc68ebab8900f4b" PRIMARY KEY ("id")); COMMENT ON COLUMN "note_scheduled"."createdAt" IS 'The created date of the Note.'; COMMENT ON COLUMN "note_scheduled"."scheduledAt" IS 'The scheduled date of the Note.'; COMMENT ON COLUMN "note_scheduled"."userId" IS 'The ID of author.'`);
await queryRunner.query(`CREATE INDEX "IDX_7ddf8710a9faee81081592ec35" ON "note_scheduled" ("createdAt") `);
await queryRunner.query(`CREATE INDEX "IDX_bbe52891059217fc31e73e84e2" ON "note_scheduled" ("scheduledAt") `);
await queryRunner.query(`CREATE INDEX "IDX_b148b24837cc7a2707ae1f0975" ON "note_scheduled" ("userId") `);
await queryRunner.query(`CREATE UNIQUE INDEX "IDX_dfeab22d6bbc4799193997553a" ON "note_scheduled" ("userId", "scheduledAt") `);
await queryRunner.query(`ALTER TABLE "note_scheduled" ADD CONSTRAINT "FK_b148b24837cc7a2707ae1f0975a" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION`);
}
async down(queryRunner) {
await queryRunner.query(`ALTER TABLE "note_scheduled" DROP CONSTRAINT "FK_b148b24837cc7a2707ae1f0975a"`);
await queryRunner.query(`DROP INDEX "public"."IDX_dfeab22d6bbc4799193997553a"`);
await queryRunner.query(`DROP INDEX "public"."IDX_b148b24837cc7a2707ae1f0975"`);
await queryRunner.query(`DROP INDEX "public"."IDX_bbe52891059217fc31e73e84e2"`);
await queryRunner.query(`DROP INDEX "public"."IDX_7ddf8710a9faee81081592ec35"`);
await queryRunner.query(`DROP TABLE "note_scheduled"`);
}
}

View file

@ -33,16 +33,16 @@
"generate-api-json": "pnpm build && node ./scripts/generate_api_json.js"
},
"optionalDependencies": {
"@swc/core-darwin-arm64": "1.10.3",
"@swc/core-darwin-x64": "1.10.3",
"@swc/core-linux-arm-gnueabihf": "1.10.3",
"@swc/core-linux-arm64-gnu": "1.10.3",
"@swc/core-linux-arm64-musl": "1.10.3",
"@swc/core-linux-x64-gnu": "1.10.3",
"@swc/core-linux-x64-musl": "1.10.3",
"@swc/core-win32-arm64-msvc": "1.10.3",
"@swc/core-win32-ia32-msvc": "1.10.3",
"@swc/core-win32-x64-msvc": "1.10.3",
"@swc/core-darwin-arm64": "1.10.7",
"@swc/core-darwin-x64": "1.10.7",
"@swc/core-linux-arm-gnueabihf": "1.10.7",
"@swc/core-linux-arm64-gnu": "1.10.7",
"@swc/core-linux-arm64-musl": "1.10.7",
"@swc/core-linux-x64-gnu": "1.10.7",
"@swc/core-linux-x64-musl": "1.10.7",
"@swc/core-win32-arm64-msvc": "1.10.7",
"@swc/core-win32-ia32-msvc": "1.10.7",
"@swc/core-win32-x64-msvc": "1.10.7",
"@tensorflow/tfjs": "4.22.0",
"@tensorflow/tfjs-node": "4.22.0",
"bufferutil": "4.0.9",
@ -63,22 +63,22 @@
},
"dependencies": {
"@authenio/samlify-node-xmllint": "2.0.0",
"@aws-sdk/client-s3": "3.717.0",
"@aws-sdk/lib-storage": "3.717.0",
"@bull-board/api": "6.5.4",
"@bull-board/fastify": "6.5.4",
"@bull-board/ui": "6.5.4",
"@aws-sdk/client-s3": "3.729.0",
"@aws-sdk/lib-storage": "3.729.0",
"@bull-board/api": "6.6.2",
"@bull-board/fastify": "6.6.2",
"@bull-board/ui": "6.6.2",
"@discordapp/twemoji": "15.1.0",
"@elastic/elasticsearch": "8.17.0",
"@fastify/accepts": "5.0.2",
"@fastify/cookie": "11.0.1",
"@fastify/cors": "10.0.1",
"@fastify/express": "4.0.1",
"@fastify/formbody": "8.0.1",
"@fastify/http-proxy": "11.0.0",
"@fastify/multipart": "9.0.1",
"@fastify/static": "8.0.3",
"@fastify/view": "10.0.1",
"@fastify/cookie": "11.0.2",
"@fastify/cors": "10.0.2",
"@fastify/express": "4.0.2",
"@fastify/formbody": "8.0.2",
"@fastify/http-proxy": "11.0.1",
"@fastify/multipart": "9.0.2",
"@fastify/static": "8.0.4",
"@fastify/view": "10.0.2",
"@misskey-dev/sharp-read-bmp": "1.2.0",
"@misskey-dev/summaly": "github:MisskeyIO/summaly#5.1.3",
"@napi-rs/canvas": "0.1.65",
@ -86,11 +86,11 @@
"@nestjs/core": "10.4.15",
"@nestjs/testing": "10.4.15",
"@peertube/http-signature": "1.7.0",
"@simplewebauthn/server": "13.0.0",
"@simplewebauthn/server": "13.1.0",
"@sinonjs/fake-timers": "11.3.1",
"@smithy/node-http-handler": "3.3.3",
"@swc/cli": "0.5.2",
"@swc/core": "1.10.3",
"@smithy/node-http-handler": "4.0.2",
"@swc/cli": "0.6.0",
"@swc/core": "1.10.7",
"@twemoji/parser": "15.1.1",
"accepts": "1.3.8",
"ajv": "8.17.1",
@ -99,7 +99,7 @@
"bcryptjs": "2.4.3",
"blurhash": "2.0.5",
"body-parser": "1.20.3",
"bullmq": "5.34.5",
"bullmq": "5.34.10",
"cacheable-lookup": "7.0.0",
"cbor": "10.0.3",
"chalk": "5.4.1",
@ -110,11 +110,11 @@
"content-disposition": "0.5.4",
"date-fns": "4.1.0",
"deep-email-validator": "0.1.21",
"fastify": "5.2.0",
"fastify-http-errors-enhanced": "6.0.0",
"fastify": "5.2.1",
"fastify-http-errors-enhanced": "6.0.1",
"fastify-raw-body": "5.0.0",
"feed": "4.2.2",
"file-type": "19.6.0",
"file-type": "20.0.0",
"fluent-ffmpeg": "2.1.3",
"form-data": "4.0.1",
"got": "14.4.5",
@ -127,11 +127,11 @@
"is-svg": "5.1.0",
"jose": "5.9.6",
"js-yaml": "4.1.0",
"jsdom": "25.0.1",
"jsdom": "26.0.0",
"json5": "2.2.3",
"jsonld": "8.3.3",
"jsrsasign": "11.1.0",
"meilisearch": "0.47.0",
"meilisearch": "0.48.0",
"mfm-js": "0.24.0",
"microformats-parser": "2.0.2",
"mime-types": "2.1.35",
@ -163,25 +163,24 @@
"random-seed": "0.3.0",
"ratelimiter": "3.4.1",
"re2": "1.21.4",
"redis-lock": "0.1.4",
"reflect-metadata": "0.2.2",
"rename": "1.0.4",
"rss-parser": "3.13.0",
"rxjs": "7.8.1",
"samlify": "2.8.11",
"sanitize-html": "2.14.0",
"secure-json-parse": "3.0.1",
"secure-json-parse": "3.0.2",
"sharp": "0.33.5",
"slacc": "0.0.10",
"strict-event-emitter-types": "2.0.0",
"stringz": "2.1.0",
"systeminformation": "5.23.23",
"systeminformation": "5.25.11",
"tinycolor2": "1.6.0",
"tmp": "0.2.3",
"tsc-alias": "1.8.10",
"tsconfig-paths": "4.2.0",
"typeorm": "0.3.20",
"typescript": "5.7.2",
"typescript": "5.7.3",
"ulid": "2.3.0",
"vary": "1.1.2",
"web-push": "3.6.7",
@ -210,7 +209,7 @@
"@types/jsrsasign": "10.5.15",
"@types/mime-types": "2.1.4",
"@types/ms": "0.7.34",
"@types/node": "22.10.2",
"@types/node": "22.10.7",
"@types/node-forge": "1.3.11",
"@types/nodemailer": "6.4.17",
"@types/oauth": "0.9.6",

View file

@ -1,13 +0,0 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
declare module 'redis-lock' {
import type Redis from 'ioredis';
type Lock = (lockName: string, timeout?: number, taskToPerform?: () => Promise<void>) => void;
function redisLock(client: Redis.Redis, retryDelay: number): Lock;
export = redisLock;
}

View file

@ -1,44 +0,0 @@
/*
* SPDX-FileCopyrightText: syuilo and misskey-project
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { promisify } from 'node:util';
import { Inject, Injectable } from '@nestjs/common';
import redisLock from 'redis-lock';
import * as Redis from 'ioredis';
import { DI } from '@/di-symbols.js';
import { bindThis } from '@/decorators.js';
/**
* Retry delay (ms) for lock acquisition
*/
const retryDelay = 100;
@Injectable()
export class AppLockService {
private lock: (key: string, timeout?: number, _?: (() => Promise<void>) | undefined) => Promise<() => void>;
constructor(
@Inject(DI.redis)
private redisClient: Redis.Redis,
) {
this.lock = promisify(redisLock(this.redisClient, retryDelay));
}
/**
* Get AP Object lock
* @param uri AP object ID
* @param timeout Lock timeout (ms), The timeout releases previous lock.
* @returns Unlock function
*/
@bindThis
public getApLock(uri: string, timeout = 30 * 1000): Promise<() => void> {
return this.lock(`ap-object:${uri}`, timeout);
}
@bindThis
public getChartInsertLock(lockKey: string, timeout = 30 * 1000): Promise<() => void> {
return this.lock(`chart-insert:${lockKey}`, timeout);
}
}

View file

@ -10,7 +10,6 @@ import { AccountUpdateService } from './AccountUpdateService.js';
import { AiService } from './AiService.js';
import { AnnouncementService } from './AnnouncementService.js';
import { AntennaService } from './AntennaService.js';
import { AppLockService } from './AppLockService.js';
import { AchievementService } from './AchievementService.js';
import { AvatarDecorationService } from './AvatarDecorationService.js';
import { CaptchaService } from './CaptchaService.js';
@ -105,6 +104,7 @@ import { UserAccountMoveLogEntityService } from './entities/UserAccountMoveLogEn
import { MutingEntityService } from './entities/MutingEntityService.js';
import { RenoteMutingEntityService } from './entities/RenoteMutingEntityService.js';
import { NoteEntityService } from './entities/NoteEntityService.js';
import { ScheduledNoteEntityService } from './entities/ScheduledNoteEntityService.js';
import { NoteFavoriteEntityService } from './entities/NoteFavoriteEntityService.js';
import { NoteReactionEntityService } from './entities/NoteReactionEntityService.js';
import { NotificationEntityService } from './entities/NotificationEntityService.js';
@ -150,7 +150,6 @@ const $AccountUpdateService: Provider = { provide: 'AccountUpdateService', useEx
const $AiService: Provider = { provide: 'AiService', useExisting: AiService };
const $AnnouncementService: Provider = { provide: 'AnnouncementService', useExisting: AnnouncementService };
const $AntennaService: Provider = { provide: 'AntennaService', useExisting: AntennaService };
const $AppLockService: Provider = { provide: 'AppLockService', useExisting: AppLockService };
const $AchievementService: Provider = { provide: 'AchievementService', useExisting: AchievementService };
const $AvatarDecorationService: Provider = { provide: 'AvatarDecorationService', useExisting: AvatarDecorationService };
const $CaptchaService: Provider = { provide: 'CaptchaService', useExisting: CaptchaService };
@ -248,6 +247,7 @@ const $UserAccountMoveLogEntityService: Provider = { provide: 'UserAccountMoveLo
const $MutingEntityService: Provider = { provide: 'MutingEntityService', useExisting: MutingEntityService };
const $RenoteMutingEntityService: Provider = { provide: 'RenoteMutingEntityService', useExisting: RenoteMutingEntityService };
const $NoteEntityService: Provider = { provide: 'NoteEntityService', useExisting: NoteEntityService };
const $ScheduledNoteEntityService: Provider = { provide: 'ScheduledNoteEntityService', useExisting: ScheduledNoteEntityService };
const $NoteFavoriteEntityService: Provider = { provide: 'NoteFavoriteEntityService', useExisting: NoteFavoriteEntityService };
const $NoteReactionEntityService: Provider = { provide: 'NoteReactionEntityService', useExisting: NoteReactionEntityService };
const $NotificationEntityService: Provider = { provide: 'NotificationEntityService', useExisting: NotificationEntityService };
@ -293,7 +293,6 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
AiService,
AnnouncementService,
AntennaService,
AppLockService,
AchievementService,
AvatarDecorationService,
CaptchaService,
@ -389,6 +388,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
MutingEntityService,
RenoteMutingEntityService,
NoteEntityService,
ScheduledNoteEntityService,
NoteFavoriteEntityService,
NoteReactionEntityService,
NotificationEntityService,
@ -433,7 +433,6 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
$AiService,
$AnnouncementService,
$AntennaService,
$AppLockService,
$AchievementService,
$AvatarDecorationService,
$CaptchaService,
@ -529,6 +528,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
$MutingEntityService,
$RenoteMutingEntityService,
$NoteEntityService,
$ScheduledNoteEntityService,
$NoteFavoriteEntityService,
$NoteReactionEntityService,
$NotificationEntityService,
@ -571,7 +571,6 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
AiService,
AnnouncementService,
AntennaService,
AppLockService,
AchievementService,
AvatarDecorationService,
CaptchaService,
@ -666,6 +665,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
MutingEntityService,
RenoteMutingEntityService,
NoteEntityService,
ScheduledNoteEntityService,
NoteFavoriteEntityService,
NoteReactionEntityService,
NotificationEntityService,
@ -710,7 +710,6 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
$AiService,
$AnnouncementService,
$AntennaService,
$AppLockService,
$AchievementService,
$AvatarDecorationService,
$CaptchaService,
@ -805,6 +804,7 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
$MutingEntityService,
$RenoteMutingEntityService,
$NoteEntityService,
$ScheduledNoteEntityService,
$NoteFavoriteEntityService,
$NoteReactionEntityService,
$NotificationEntityService,

View file

@ -9,7 +9,7 @@ import { join } from 'node:path';
import * as stream from 'node:stream/promises';
import { Injectable } from '@nestjs/common';
import { FSWatcher } from 'chokidar';
import * as fileType from 'file-type';
import { fileTypeFromFile } from 'file-type';
import FFmpeg from 'fluent-ffmpeg';
import isSvg from 'is-svg';
import probeImageSize from 'probe-image-size';
@ -309,7 +309,7 @@ export class FileInfoService {
}
@bindThis
public fixMime(mime: string | fileType.MimeType): string {
public fixMime(mime: string): string {
// see https://github.com/misskey-dev/misskey/pull/10686
if (mime === 'audio/x-flac') {
return 'audio/flac';
@ -363,7 +363,7 @@ export class FileInfoService {
return TYPE_OCTET_STREAM;
}
const type = await fileType.fileTypeFromFile(path);
const type = await fileTypeFromFile(path);
if (type) {
// XMLはSVGかもしれない

View file

@ -13,16 +13,28 @@ import { extractCustomEmojisFromMfm } from '@/misc/extract-custom-emojis-from-mf
import { extractHashtags } from '@/misc/extract-hashtags.js';
import type { IMentionedRemoteUsers } from '@/models/Note.js';
import { MiNote } from '@/models/Note.js';
import type { ChannelFollowingsRepository, ChannelsRepository, FollowingsRepository, InstancesRepository, MiFollowing, NotesRepository, NoteThreadMutingsRepository, UserListMembershipsRepository, UserProfilesRepository, UsersRepository } from '@/models/_.js';
import { MiScheduledNote } from '@/models/ScheduledNote.js';
import type {
ChannelFollowingsRepository,
ChannelsRepository,
FollowingsRepository,
InstancesRepository,
MiFollowing,
NotesRepository,
NoteThreadMutingsRepository,
ScheduledNotesRepository,
UserListMembershipsRepository,
UserProfilesRepository,
UsersRepository
} from '@/models/_.js';
import type { MiDriveFile } from '@/models/DriveFile.js';
import type { MiApp } from '@/models/App.js';
import { concat } from '@/misc/prelude/array.js';
import { IdService } from '@/core/IdService.js';
import type { MiUser, MiLocalUser, MiRemoteUser } from '@/models/User.js';
import type { IPoll } from '@/models/Poll.js';
import { MiPoll } from '@/models/Poll.js';
import type { NoteCreateOption, MinimumUser } from '@/types.js';
import { isDuplicateKeyValueError } from '@/misc/is-duplicate-key-value-error.js';
import type { MiChannel } from '@/models/Channel.js';
import { normalizeForSearch } from '@/misc/normalize-for-search.js';
import { RelayService } from '@/core/RelayService.js';
import { FederatedInstanceService } from '@/core/FederatedInstanceService.js';
@ -118,35 +130,6 @@ class NotificationManager {
}
}
type MinimumUser = {
id: MiUser['id'];
host: MiUser['host'];
username: MiUser['username'];
uri: MiUser['uri'];
};
type Option = {
createdAt?: Date | null;
name?: string | null;
text?: string | null;
reply?: MiNote | null;
renote?: MiNote | null;
files?: MiDriveFile[] | null;
poll?: IPoll | null;
localOnly?: boolean | null;
reactionAcceptance?: MiNote['reactionAcceptance'];
cw?: string | null;
visibility?: string;
visibleUsers?: MinimumUser[] | null;
channel?: MiChannel | null;
apMentions?: MinimumUser[] | null;
apHashtags?: string[] | null;
apEmojis?: string[] | null;
uri?: string | null;
url?: string | null;
app?: MiApp | null;
};
@Injectable()
export class NoteCreateService implements OnApplicationShutdown {
private logger: Logger;
@ -169,6 +152,9 @@ export class NoteCreateService implements OnApplicationShutdown {
@Inject(DI.notesRepository)
private notesRepository: NotesRepository,
@Inject(DI.scheduledNotesRepository)
private scheduledNotesRepository: ScheduledNotesRepository,
@Inject(DI.instancesRepository)
private instancesRepository: InstancesRepository,
@ -229,7 +215,7 @@ export class NoteCreateService implements OnApplicationShutdown {
host: MiUser['host'];
isBot: MiUser['isBot'];
isCat: MiUser['isCat'];
}, data: Option, silent = false): Promise<MiNote> {
}, data: NoteCreateOption, silent = false): Promise<MiNote | MiScheduledNote> {
// チャンネル外にリプライしたら対象のスコープに合わせる
// (クライアントサイドでやっても良い処理だと思うけどとりあえずサーバーサイドで)
if (data.reply && data.channel && data.reply.channelId !== data.channel.id) {
@ -425,18 +411,39 @@ export class NoteCreateService implements OnApplicationShutdown {
throw new IdentifiableError('9f466dab-c856-48cd-9e65-ff90ff750580', `Notes including mentions are limited to ${policies.mentionLimit} users.`);
}
const note = await this.insertNote(user, data, tags, emojis, mentionedUsers);
if (!data.scheduledAt) {
const note = await this.insertNote(user, data, tags, emojis, mentionedUsers);
setImmediate('post created', { signal: this.#shutdownController.signal }).then(
() => this.postNoteCreated(note, user, data, silent, tags!, mentionedUsers!),
() => { /* aborted, ignore this */ },
);
setImmediate('post created', { signal: this.#shutdownController.signal }).then(
() => this.postNoteCreated(note, user, data, silent, tags!, mentionedUsers!),
() => { /* aborted, ignore this */ },
);
return note;
return note;
} else {
if (!policies.canScheduleNote) {
throw new IdentifiableError('7cc42034-f7ab-4f7c-87b4-e00854479080', 'User has no permission to schedule notes.');
}
if ((data.scheduledAt.getTime() - Date.now()) / 86_400_000 > policies.scheduleNoteMaxDays) {
throw new IdentifiableError('506006cf-3092-4ae1-8145-b025001c591f', `User can schedule notes up to ${policies.scheduleNoteMaxDays} days in the future.`);
}
const scheduledCount = await this.scheduledNotesRepository.countBy({ userId: user.id });
if (scheduledCount >= policies.scheduleNoteLimit) {
throw new IdentifiableError('7fc78d25-d947-45c1-9547-02257b98cab3', `User can schedule up to ${policies.scheduleNoteLimit} notes.`);
}
const draft = await this.insertScheduledNote(user, data);
await this.queueService.createScheduledNoteJob(draft.id, draft.scheduledAt!);
return draft;
}
}
@bindThis
private async insertNote(user: { id: MiUser['id']; host: MiUser['host']; }, data: Option, tags: string[], emojis: string[], mentionedUsers: MinimumUser[]) {
private async insertNote(user: { id: MiUser['id']; host: MiUser['host']; }, data: NoteCreateOption, tags: string[], emojis: string[], mentionedUsers: MinimumUser[]) {
const insert = new MiNote({
id: this.idService.gen(data.createdAt?.getTime()),
createdAt: data.createdAt!,
@ -534,13 +541,40 @@ export class NoteCreateService implements OnApplicationShutdown {
}
}
@bindThis
private async insertScheduledNote(user: { id: MiUser['id']; host: MiUser['host']; }, data: NoteCreateOption) {
const insert = new MiScheduledNote({
id: this.idService.gen(data.createdAt?.getTime()),
createdAt: data.createdAt!,
scheduledAt: data.scheduledAt!,
userId: user.id,
draft: data,
});
// 予約投稿を作成
try {
await this.scheduledNotesRepository.insert(insert);
return insert;
} catch (e) {
// duplicate key error
if (isDuplicateKeyValueError(e)) {
throw new IdentifiableError('5ea8e4f5-9d64-4e6c-92b8-9e2b5a4756bc', 'There is already a scheduled note with the same time.');
}
this.logger.error(`Failed to create scheduled note: ${e}`, { error: e });
throw e;
}
}
@bindThis
private async postNoteCreated(note: MiNote, user: {
id: MiUser['id'];
username: MiUser['username'];
host: MiUser['host'];
isBot: MiUser['isBot'];
}, data: Option, silent: boolean, tags: string[], mentionedUsers: MinimumUser[]) {
}, data: NoteCreateOption, silent: boolean, tags: string[], mentionedUsers: MinimumUser[]) {
const meta = await this.metaService.fetch();
this.notesChart.update(note, true);
@ -792,12 +826,12 @@ export class NoteCreateService implements OnApplicationShutdown {
}
@bindThis
private isRenote(note: Option): note is Option & { renote: MiNote } {
private isRenote(note: NoteCreateOption): note is NoteCreateOption & { renote: MiNote } {
return note.renote != null;
}
@bindThis
private isQuote(note: Option): note is Option & { renote: MiNote } & (
private isQuote(note: NoteCreateOption): note is NoteCreateOption & { renote: MiNote } & (
{ text: string } | { cw: string } | { reply: MiNote } | { poll: IPoll } | { files: MiDriveFile[] }
) {
// NOTE: SYNC WITH misc/is-renote.ts
@ -873,7 +907,7 @@ export class NoteCreateService implements OnApplicationShutdown {
}
@bindThis
private async renderNoteOrRenoteActivity(data: Option, note: MiNote) {
private async renderNoteOrRenoteActivity(data: NoteCreateOption, note: MiNote) {
if (data.localOnly) return null;
const content = this.isRenote(data) && !this.isQuote(data)

View file

@ -7,6 +7,7 @@ import { randomUUID } from 'node:crypto';
import { Inject, Injectable } from '@nestjs/common';
import type { IActivity } from '@/core/activitypub/type.js';
import type { MiDriveFile } from '@/models/DriveFile.js';
import type { MiScheduledNote } from '@/models/ScheduledNote.js';
import type { MiAbuseUserReport } from '@/models/AbuseUserReport.js';
import type { MiWebhook, webhookEventTypes } from '@/models/Webhook.js';
import type { Config } from '@/config.js';
@ -34,6 +35,11 @@ export class QueueService {
@Inject('queue:objectStorage') public objectStorageQueue: ObjectStorageQueue,
@Inject('queue:webhookDeliver') public webhookDeliverQueue: WebhookDeliverQueue,
) {
this.ensureRepeatJobs();
}
@bindThis
private ensureRepeatJobs() {
this.systemQueue.add('tickCharts', {
}, {
repeat: { pattern: '55 * * * *' },
@ -69,6 +75,12 @@ export class QueueService {
repeat: { pattern: '*/5 * * * *' },
removeOnComplete: true,
});
this.systemQueue.add('checkMissingScheduledNote', {
}, {
repeat: { pattern: '*/5 * * * *' },
removeOnComplete: true,
});
}
@bindThis
@ -376,7 +388,22 @@ export class QueueService {
@bindThis
public createReportAbuseJob(report: MiAbuseUserReport) {
return this.dbQueue.add('reportAbuse', report);
return this.dbQueue.add('reportAbuse', report, {
removeOnComplete: true,
removeOnFail: true,
});
}
@bindThis
public createScheduledNoteJob(draftId: MiScheduledNote['id'], scheduledAt: Date) {
return this.systemQueue.add('scheduledNote', {
draftId,
}, {
jobId: `scheduledNote:${draftId}`,
delay: Math.max(scheduledAt.getTime() - Date.now(), 0) + Math.floor(Math.random() * 500 + 250),
removeOnComplete: true,
removeOnFail: true,
});
}
@bindThis

View file

@ -36,6 +36,9 @@ export type RolePolicies = {
gtlAvailable: boolean;
ltlAvailable: boolean;
canPublicNote: boolean;
canScheduleNote: boolean;
scheduleNoteLimit: number;
scheduleNoteMaxDays: number;
canInitiateConversation: boolean;
canCreateContent: boolean;
canUpdateContent: boolean;
@ -77,6 +80,9 @@ export const DEFAULT_POLICIES: RolePolicies = {
gtlAvailable: true,
ltlAvailable: true,
canPublicNote: true,
canScheduleNote: true,
scheduleNoteLimit: 10,
scheduleNoteMaxDays: 365,
canInitiateConversation: true,
canCreateContent: true,
canUpdateContent: true,
@ -389,6 +395,9 @@ export class RoleService implements OnApplicationShutdown, OnModuleInit {
gtlAvailable: calc('gtlAvailable', vs => vs.some(v => v === true)),
ltlAvailable: calc('ltlAvailable', vs => vs.some(v => v === true)),
canPublicNote: calc('canPublicNote', vs => vs.some(v => v === true)),
canScheduleNote: calc('canScheduleNote', vs => vs.some(v => v === true)),
scheduleNoteLimit: calc('scheduleNoteLimit', vs => Math.max(...vs)),
scheduleNoteMaxDays: calc('scheduleNoteMaxDays', vs => Math.max(...vs)),
canInitiateConversation: calc('canInitiateConversation', vs => vs.some(v => v === true)),
canCreateContent: calc('canCreateContent', vs => vs.some(v => v === true)),
canUpdateContent: calc('canUpdateContent', vs => vs.some(v => v === true)),

View file

@ -46,6 +46,8 @@ export class S3Service {
tls: meta.objectStorageUseSSL,
forcePathStyle: meta.objectStorageEndpoint ? meta.objectStorageS3ForcePathStyle : false, // AWS with endPoint omitted
requestHandler: new NodeHttpHandler(handlerOption),
requestChecksumCalculation: 'WHEN_REQUIRED',
responseChecksumValidation: 'WHEN_REQUIRED',
});
}

View file

@ -5,6 +5,7 @@
import { Inject, Injectable } from '@nestjs/common';
import { In } from 'typeorm';
import * as Redis from 'ioredis';
import { DI } from '@/di-symbols.js';
import type { Config } from '@/config.js';
import { UserFollowingService } from '@/core/UserFollowingService.js';
@ -14,8 +15,8 @@ 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 { acquireApObjectLock } from '@/misc/distributed-lock.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';
@ -49,6 +50,9 @@ export class ApInboxService {
@Inject(DI.config)
private config: Config,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
@Inject(DI.usersRepository)
private usersRepository: UsersRepository,
@ -77,7 +81,6 @@ export class ApInboxService {
private userBlockingService: UserBlockingService,
private noteCreateService: NoteCreateService,
private noteDeleteService: NoteDeleteService,
private appLockService: AppLockService,
private apResolverService: ApResolverService,
private apDbResolverService: ApDbResolverService,
private apLoggerService: ApLoggerService,
@ -312,7 +315,7 @@ export class ApInboxService {
const meta = await this.metaService.fetch();
if (this.utilityService.isItemListedIn(this.utilityService.extractHost(uri), meta.blockedHosts)) return 'skip: blocked host';
const unlock = await this.appLockService.getApLock(uri);
const unlock = await acquireApObjectLock(this.redisForTimelines, uri);
try {
// 既に同じURIを持つものが登録されていないかチェック
@ -440,7 +443,7 @@ export class ApInboxService {
}
}
const unlock = await this.appLockService.getApLock(uri);
const unlock = await acquireApObjectLock(this.redisForTimelines, uri);
try {
const exist = await this.apNoteService.fetchNote(note);
@ -543,7 +546,7 @@ export class ApInboxService {
private async deleteNote(actor: MiRemoteUser, uri: string): Promise<string> {
this.logger.info(`Deleting the Note: ${uri}`);
const unlock = await this.appLockService.getApLock(uri);
const unlock = await acquireApObjectLock(this.redisForTimelines, uri);
try {
const note = await this.apDbResolverService.getNoteFromApId(uri);
@ -813,7 +816,7 @@ export class ApInboxService {
return 'ok: Question updated';
} else if (additionalCc && isPost(object)) {
const uri = getApId(object);
const unlock = await this.appLockService.getApLock(uri);
const unlock = await acquireApObjectLock(this.redisForTimelines, uri);
try {
const exist = await this.apNoteService.fetchNote(object);

View file

@ -518,6 +518,7 @@ export class ApRendererService {
discoverable: user.isExplorable,
publicKey: this.renderKey(user, keypair, '#main-key'),
isCat: user.isCat,
speakAsCat: user.speakAsCat,
attachment: attachment.length ? attachment : undefined,
};

View file

@ -553,6 +553,9 @@ export const CONTEXTS: (string | Context)[] = [
'_misskey_votes': 'misskey:_misskey_votes',
'_misskey_summary': 'misskey:_misskey_summary',
'isCat': 'misskey:isCat',
// Firefish
firefish: "https://joinfirefish.org/ns#",
speakAsCat: "firefish:speakAsCat",
// vcard
vcard: 'http://www.w3.org/2006/vcard/ns#',
} satisfies Context,

View file

@ -5,15 +5,16 @@
import { forwardRef, Inject, Injectable } from '@nestjs/common';
import { In } from 'typeorm';
import * as Redis from 'ioredis';
import { DI } from '@/di-symbols.js';
import type { UsersRepository, PollsRepository, EmojisRepository } from '@/models/_.js';
import type { Config } from '@/config.js';
import type { MiRemoteUser } from '@/models/User.js';
import type { MiNote } from '@/models/Note.js';
import { acquireApObjectLock } from '@/misc/distributed-lock.js';
import { toArray, toSingle, unique } from '@/misc/prelude/array.js';
import type { MiEmoji } from '@/models/Emoji.js';
import { MetaService } from '@/core/MetaService.js';
import { AppLockService } from '@/core/AppLockService.js';
import type { MiDriveFile } from '@/models/DriveFile.js';
import { NoteCreateService } from '@/core/NoteCreateService.js';
import type Logger from '@/logger.js';
@ -47,6 +48,9 @@ export class ApNoteService {
@Inject(DI.config)
private config: Config,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
@Inject(DI.usersRepository)
private usersRepository: UsersRepository,
@ -70,7 +74,6 @@ export class ApNoteService {
private apImageService: ApImageService,
private apQuestionService: ApQuestionService,
private metaService: MetaService,
private appLockService: AppLockService,
private pollService: PollService,
private noteCreateService: NoteCreateService,
private apDbResolverService: ApDbResolverService,
@ -349,7 +352,7 @@ export class ApNoteService {
poll,
uri: note.id,
url: url,
}, silent);
}, silent) as MiNote;
} catch (err: any) {
if (err.name !== 'duplicated') {
throw err;
@ -379,7 +382,7 @@ export class ApNoteService {
throw new StatusError('blocked host', 451);
}
const unlock = await this.appLockService.getApLock(uri);
const unlock = await acquireApObjectLock(this.redisForTimelines, uri);
try {
//#region このサーバーに既に登録されていたらそれを返す

View file

@ -389,6 +389,7 @@ export class ApPersonService implements OnModuleInit {
tags,
isBot,
isCat: (person as any).isCat === true,
speakAsCat: (person as any).speakAsCat != null ? (person as any).speakAsCat === true : (person as any).isCat === true,
emojis,
})) as MiRemoteUser;
@ -562,12 +563,13 @@ export class ApPersonService implements OnModuleInit {
tags,
isBot: getApType(object) === 'Service' || getApType(object) === 'Application',
isCat: (person as any).isCat === true,
speakAsCat: (person as any).speakAsCat != null ? (person as any).speakAsCat === true : (person as any).isCat === true,
isLocked: person.manuallyApprovesFollowers,
movedToUri: person.movedTo ?? null,
alsoKnownAs: person.alsoKnownAs ?? null,
isExplorable: person.discoverable,
...((policy.canUpdateAvatar || policy.canUpdateBanner) ? await this.resolveAvatarAndBanner(exist, policy.canUpdateAvatar ? person.icon : exist.avatarUrl, policy.canUpdateBanner ? person.image : exist.bannerUrl).catch(() => ({})) : {}),
} as Partial<MiRemoteUser> & Pick<MiRemoteUser, 'isBot' | 'isCat' | 'isLocked' | 'movedToUri' | 'alsoKnownAs' | 'isExplorable'>;
} as Partial<MiRemoteUser> & Pick<MiRemoteUser, 'isBot' | 'isCat' | 'speakAsCat' | 'isLocked' | 'movedToUri' | 'alsoKnownAs' | 'isExplorable'>;
const moving = ((): boolean => {
// 移行先がない→ある

View file

@ -5,11 +5,12 @@
import { Injectable, Inject } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { AppLockService } from '@/core/AppLockService.js';
import * as Redis from 'ioredis';
import type { MiUser } from '@/models/User.js';
import { DI } from '@/di-symbols.js';
import { bindThis } from '@/decorators.js';
import { IdService } from '@/core/IdService.js';
import { acquireChartInsertLock } from '@/misc/distributed-lock.js';
import Chart from '../core.js';
import { ChartLoggerService } from '../ChartLoggerService.js';
import { name, schema } from './entities/active-users.js';
@ -28,11 +29,13 @@ export default class ActiveUsersChart extends Chart<typeof schema> { // eslint-d
@Inject(DI.db)
private db: DataSource,
private appLockService: AppLockService,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
private chartLoggerService: ChartLoggerService,
private idService: IdService,
) {
super(db, (k) => appLockService.getChartInsertLock(k), chartLoggerService.logger, name, schema);
super(db, (k) => acquireChartInsertLock(redisForTimelines, k), chartLoggerService.logger, name, schema);
}
protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> {

View file

@ -5,9 +5,10 @@
import { Injectable, Inject } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { AppLockService } from '@/core/AppLockService.js';
import * as Redis from 'ioredis';
import { DI } from '@/di-symbols.js';
import { bindThis } from '@/decorators.js';
import { acquireChartInsertLock } from '@/misc/distributed-lock.js';
import Chart from '../core.js';
import { ChartLoggerService } from '../ChartLoggerService.js';
import { name, schema } from './entities/ap-request.js';
@ -22,10 +23,12 @@ export default class ApRequestChart extends Chart<typeof schema> { // eslint-dis
@Inject(DI.db)
private db: DataSource,
private appLockService: AppLockService,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
private chartLoggerService: ChartLoggerService,
) {
super(db, (k) => appLockService.getChartInsertLock(k), chartLoggerService.logger, name, schema);
super(db, (k) => acquireChartInsertLock(redisForTimelines, k), chartLoggerService.logger, name, schema);
}
protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> {

View file

@ -5,10 +5,11 @@
import { Injectable, Inject } from '@nestjs/common';
import { DataSource } from 'typeorm';
import * as Redis from 'ioredis';
import type { MiDriveFile } from '@/models/DriveFile.js';
import { AppLockService } from '@/core/AppLockService.js';
import { DI } from '@/di-symbols.js';
import { bindThis } from '@/decorators.js';
import { acquireChartInsertLock } from '@/misc/distributed-lock.js';
import Chart from '../core.js';
import { ChartLoggerService } from '../ChartLoggerService.js';
import { name, schema } from './entities/drive.js';
@ -23,10 +24,12 @@ export default class DriveChart extends Chart<typeof schema> { // eslint-disable
@Inject(DI.db)
private db: DataSource,
private appLockService: AppLockService,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
private chartLoggerService: ChartLoggerService,
) {
super(db, (k) => appLockService.getChartInsertLock(k), chartLoggerService.logger, name, schema);
super(db, (k) => acquireChartInsertLock(redisForTimelines, k), chartLoggerService.logger, name, schema);
}
protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> {

View file

@ -5,11 +5,12 @@
import { Injectable, Inject } from '@nestjs/common';
import { DataSource } from 'typeorm';
import * as Redis from 'ioredis';
import type { FollowingsRepository, InstancesRepository } from '@/models/_.js';
import { AppLockService } from '@/core/AppLockService.js';
import { DI } from '@/di-symbols.js';
import { MetaService } from '@/core/MetaService.js';
import { bindThis } from '@/decorators.js';
import { acquireChartInsertLock } from '@/misc/distributed-lock.js';
import Chart from '../core.js';
import { ChartLoggerService } from '../ChartLoggerService.js';
import { name, schema } from './entities/federation.js';
@ -24,6 +25,9 @@ export default class FederationChart extends Chart<typeof schema> { // eslint-di
@Inject(DI.db)
private db: DataSource,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
@Inject(DI.followingsRepository)
private followingsRepository: FollowingsRepository,
@ -31,10 +35,9 @@ export default class FederationChart extends Chart<typeof schema> { // eslint-di
private instancesRepository: InstancesRepository,
private metaService: MetaService,
private appLockService: AppLockService,
private chartLoggerService: ChartLoggerService,
) {
super(db, (k) => appLockService.getChartInsertLock(k), chartLoggerService.logger, name, schema);
super(db, (k) => acquireChartInsertLock(redisForTimelines, k), chartLoggerService.logger, name, schema);
}
protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> {

View file

@ -5,13 +5,14 @@
import { Injectable, Inject } from '@nestjs/common';
import { DataSource } from 'typeorm';
import * as Redis from 'ioredis';
import type { DriveFilesRepository, FollowingsRepository, UsersRepository, NotesRepository } from '@/models/_.js';
import type { MiDriveFile } from '@/models/DriveFile.js';
import type { MiNote } from '@/models/Note.js';
import { AppLockService } from '@/core/AppLockService.js';
import { DI } from '@/di-symbols.js';
import { UtilityService } from '@/core/UtilityService.js';
import { bindThis } from '@/decorators.js';
import { acquireChartInsertLock } from '@/misc/distributed-lock.js';
import Chart from '../core.js';
import { ChartLoggerService } from '../ChartLoggerService.js';
import { name, schema } from './entities/instance.js';
@ -26,6 +27,9 @@ export default class InstanceChart extends Chart<typeof schema> { // eslint-disa
@Inject(DI.db)
private db: DataSource,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
@Inject(DI.usersRepository)
private usersRepository: UsersRepository,
@ -39,10 +43,9 @@ export default class InstanceChart extends Chart<typeof schema> { // eslint-disa
private followingsRepository: FollowingsRepository,
private utilityService: UtilityService,
private appLockService: AppLockService,
private chartLoggerService: ChartLoggerService,
) {
super(db, (k) => appLockService.getChartInsertLock(k), chartLoggerService.logger, name, schema, true);
super(db, (k) => acquireChartInsertLock(redisForTimelines, k), chartLoggerService.logger, name, schema, true);
}
protected async tickMajor(group: string): Promise<Partial<KVs<typeof schema>>> {

View file

@ -5,11 +5,12 @@
import { Injectable, Inject } from '@nestjs/common';
import { Not, IsNull, DataSource } from 'typeorm';
import * as Redis from 'ioredis';
import type { NotesRepository } from '@/models/_.js';
import type { MiNote } from '@/models/Note.js';
import { AppLockService } from '@/core/AppLockService.js';
import { DI } from '@/di-symbols.js';
import { bindThis } from '@/decorators.js';
import { acquireChartInsertLock } from '@/misc/distributed-lock.js';
import Chart from '../core.js';
import { ChartLoggerService } from '../ChartLoggerService.js';
import { name, schema } from './entities/notes.js';
@ -24,13 +25,15 @@ export default class NotesChart extends Chart<typeof schema> { // eslint-disable
@Inject(DI.db)
private db: DataSource,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
@Inject(DI.notesRepository)
private notesRepository: NotesRepository,
private appLockService: AppLockService,
private chartLoggerService: ChartLoggerService,
) {
super(db, (k) => appLockService.getChartInsertLock(k), chartLoggerService.logger, name, schema);
super(db, (k) => acquireChartInsertLock(redisForTimelines, k), chartLoggerService.logger, name, schema);
}
protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> {

View file

@ -5,12 +5,13 @@
import { Injectable, Inject } from '@nestjs/common';
import { DataSource } from 'typeorm';
import * as Redis from 'ioredis';
import type { DriveFilesRepository } from '@/models/_.js';
import type { MiDriveFile } from '@/models/DriveFile.js';
import { AppLockService } from '@/core/AppLockService.js';
import { DI } from '@/di-symbols.js';
import { DriveFileEntityService } from '@/core/entities/DriveFileEntityService.js';
import { bindThis } from '@/decorators.js';
import { acquireChartInsertLock } from '@/misc/distributed-lock.js';
import Chart from '../core.js';
import { ChartLoggerService } from '../ChartLoggerService.js';
import { name, schema } from './entities/per-user-drive.js';
@ -25,14 +26,16 @@ export default class PerUserDriveChart extends Chart<typeof schema> { // eslint-
@Inject(DI.db)
private db: DataSource,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
@Inject(DI.driveFilesRepository)
private driveFilesRepository: DriveFilesRepository,
private appLockService: AppLockService,
private driveFileEntityService: DriveFileEntityService,
private chartLoggerService: ChartLoggerService,
) {
super(db, (k) => appLockService.getChartInsertLock(k), chartLoggerService.logger, name, schema, true);
super(db, (k) => acquireChartInsertLock(redisForTimelines, k), chartLoggerService.logger, name, schema, true);
}
protected async tickMajor(group: string): Promise<Partial<KVs<typeof schema>>> {

View file

@ -5,12 +5,13 @@
import { Injectable, Inject } from '@nestjs/common';
import { Not, IsNull, DataSource } from 'typeorm';
import * as Redis from 'ioredis';
import type { MiUser } from '@/models/User.js';
import { AppLockService } from '@/core/AppLockService.js';
import { DI } from '@/di-symbols.js';
import { UserEntityService } from '@/core/entities/UserEntityService.js';
import type { FollowingsRepository } from '@/models/_.js';
import { bindThis } from '@/decorators.js';
import { acquireChartInsertLock } from '@/misc/distributed-lock.js';
import Chart from '../core.js';
import { ChartLoggerService } from '../ChartLoggerService.js';
import { name, schema } from './entities/per-user-following.js';
@ -25,14 +26,16 @@ export default class PerUserFollowingChart extends Chart<typeof schema> { // esl
@Inject(DI.db)
private db: DataSource,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
@Inject(DI.followingsRepository)
private followingsRepository: FollowingsRepository,
private appLockService: AppLockService,
private userEntityService: UserEntityService,
private chartLoggerService: ChartLoggerService,
) {
super(db, (k) => appLockService.getChartInsertLock(k), chartLoggerService.logger, name, schema, true);
super(db, (k) => acquireChartInsertLock(redisForTimelines, k), chartLoggerService.logger, name, schema, true);
}
protected async tickMajor(group: string): Promise<Partial<KVs<typeof schema>>> {

View file

@ -5,12 +5,13 @@
import { Injectable, Inject } from '@nestjs/common';
import { DataSource } from 'typeorm';
import * as Redis from 'ioredis';
import type { MiUser } from '@/models/User.js';
import type { MiNote } from '@/models/Note.js';
import { AppLockService } from '@/core/AppLockService.js';
import { DI } from '@/di-symbols.js';
import type { NotesRepository } from '@/models/_.js';
import { bindThis } from '@/decorators.js';
import { acquireChartInsertLock } from '@/misc/distributed-lock.js';
import Chart from '../core.js';
import { ChartLoggerService } from '../ChartLoggerService.js';
import { name, schema } from './entities/per-user-notes.js';
@ -25,13 +26,15 @@ export default class PerUserNotesChart extends Chart<typeof schema> { // eslint-
@Inject(DI.db)
private db: DataSource,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
@Inject(DI.notesRepository)
private notesRepository: NotesRepository,
private appLockService: AppLockService,
private chartLoggerService: ChartLoggerService,
) {
super(db, (k) => appLockService.getChartInsertLock(k), chartLoggerService.logger, name, schema, true);
super(db, (k) => acquireChartInsertLock(redisForTimelines, k), chartLoggerService.logger, name, schema, true);
}
protected async tickMajor(group: string): Promise<Partial<KVs<typeof schema>>> {

View file

@ -5,11 +5,12 @@
import { Injectable, Inject } from '@nestjs/common';
import { DataSource } from 'typeorm';
import * as Redis from 'ioredis';
import type { MiUser } from '@/models/User.js';
import { AppLockService } from '@/core/AppLockService.js';
import { addTime, dateUTC, subtractTime } from '@/misc/prelude/time.js';
import { DI } from '@/di-symbols.js';
import { bindThis } from '@/decorators.js';
import { acquireChartInsertLock } from '@/misc/distributed-lock.js';
import Chart from '../core.js';
import { ChartLoggerService } from '../ChartLoggerService.js';
import { name, schema } from './entities/per-user-pv.js';
@ -24,10 +25,12 @@ export default class PerUserPvChart extends Chart<typeof schema> { // eslint-dis
@Inject(DI.db)
private db: DataSource,
private appLockService: AppLockService,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
private chartLoggerService: ChartLoggerService,
) {
super(db, (k) => appLockService.getChartInsertLock(k), chartLoggerService.logger, name, schema, true);
super(db, (k) => acquireChartInsertLock(redisForTimelines, k), chartLoggerService.logger, name, schema, true);
}
protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> {

View file

@ -5,12 +5,13 @@
import { Injectable, Inject } from '@nestjs/common';
import { DataSource } from 'typeorm';
import * as Redis from 'ioredis';
import type { MiUser } from '@/models/User.js';
import type { MiNote } from '@/models/Note.js';
import { AppLockService } from '@/core/AppLockService.js';
import { DI } from '@/di-symbols.js';
import { UserEntityService } from '@/core/entities/UserEntityService.js';
import { bindThis } from '@/decorators.js';
import { acquireChartInsertLock } from '@/misc/distributed-lock.js';
import Chart from '../core.js';
import { ChartLoggerService } from '../ChartLoggerService.js';
import { name, schema } from './entities/per-user-reactions.js';
@ -25,11 +26,13 @@ export default class PerUserReactionsChart extends Chart<typeof schema> { // esl
@Inject(DI.db)
private db: DataSource,
private appLockService: AppLockService,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
private userEntityService: UserEntityService,
private chartLoggerService: ChartLoggerService,
) {
super(db, (k) => appLockService.getChartInsertLock(k), chartLoggerService.logger, name, schema, true);
super(db, (k) => acquireChartInsertLock(redisForTimelines, k), chartLoggerService.logger, name, schema, true);
}
protected async tickMajor(group: string): Promise<Partial<KVs<typeof schema>>> {

View file

@ -5,10 +5,11 @@
import { Injectable, Inject } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { AppLockService } from '@/core/AppLockService.js';
import * as Redis from 'ioredis';
import { DI } from '@/di-symbols.js';
import Logger from '@/logger.js';
import { bindThis } from '@/decorators.js';
import { acquireChartInsertLock } from '@/misc/distributed-lock.js';
import Chart from '../core.js';
import { name, schema } from './entities/test-grouped.js';
import type { KVs } from '../core.js';
@ -24,10 +25,12 @@ export default class TestGroupedChart extends Chart<typeof schema> { // eslint-d
@Inject(DI.db)
private db: DataSource,
private appLockService: AppLockService,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
logger: Logger,
) {
super(db, (k) => appLockService.getChartInsertLock(k), logger, name, schema, true);
super(db, (k) => acquireChartInsertLock(redisForTimelines, k), logger, name, schema, true);
}
protected async tickMajor(group: string): Promise<Partial<KVs<typeof schema>>> {

View file

@ -5,10 +5,11 @@
import { Injectable, Inject } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { AppLockService } from '@/core/AppLockService.js';
import * as Redis from 'ioredis';
import { DI } from '@/di-symbols.js';
import Logger from '@/logger.js';
import { bindThis } from '@/decorators.js';
import { acquireChartInsertLock } from '@/misc/distributed-lock.js';
import Chart from '../core.js';
import { name, schema } from './entities/test-intersection.js';
import type { KVs } from '../core.js';
@ -22,10 +23,12 @@ export default class TestIntersectionChart extends Chart<typeof schema> { // esl
@Inject(DI.db)
private db: DataSource,
private appLockService: AppLockService,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
logger: Logger,
) {
super(db, (k) => appLockService.getChartInsertLock(k), logger, name, schema);
super(db, (k) => acquireChartInsertLock(redisForTimelines, k), logger, name, schema);
}
protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> {

View file

@ -5,10 +5,11 @@
import { Injectable, Inject } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { AppLockService } from '@/core/AppLockService.js';
import * as Redis from 'ioredis';
import { DI } from '@/di-symbols.js';
import Logger from '@/logger.js';
import { bindThis } from '@/decorators.js';
import { acquireChartInsertLock } from '@/misc/distributed-lock.js';
import Chart from '../core.js';
import { name, schema } from './entities/test-unique.js';
import type { KVs } from '../core.js';
@ -22,10 +23,12 @@ export default class TestUniqueChart extends Chart<typeof schema> { // eslint-di
@Inject(DI.db)
private db: DataSource,
private appLockService: AppLockService,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
logger: Logger,
) {
super(db, (k) => appLockService.getChartInsertLock(k), logger, name, schema);
super(db, (k) => acquireChartInsertLock(redisForTimelines, k), logger, name, schema);
}
protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> {

View file

@ -5,10 +5,11 @@
import { Injectable, Inject } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { AppLockService } from '@/core/AppLockService.js';
import * as Redis from 'ioredis';
import { DI } from '@/di-symbols.js';
import Logger from '@/logger.js';
import { bindThis } from '@/decorators.js';
import { acquireChartInsertLock } from '@/misc/distributed-lock.js';
import Chart from '../core.js';
import { name, schema } from './entities/test.js';
import type { KVs } from '../core.js';
@ -24,10 +25,12 @@ export default class TestChart extends Chart<typeof schema> { // eslint-disable-
@Inject(DI.db)
private db: DataSource,
private appLockService: AppLockService,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
logger: Logger,
) {
super(db, (k) => appLockService.getChartInsertLock(k), logger, name, schema);
super(db, (k) => acquireChartInsertLock(redisForTimelines, k), logger, name, schema);
}
protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> {

View file

@ -5,12 +5,13 @@
import { Injectable, Inject } from '@nestjs/common';
import { Not, IsNull, DataSource } from 'typeorm';
import * as Redis from 'ioredis';
import type { MiUser } from '@/models/User.js';
import { AppLockService } from '@/core/AppLockService.js';
import { DI } from '@/di-symbols.js';
import { UserEntityService } from '@/core/entities/UserEntityService.js';
import type { UsersRepository } from '@/models/_.js';
import { bindThis } from '@/decorators.js';
import { acquireChartInsertLock } from '@/misc/distributed-lock.js';
import Chart from '../core.js';
import { ChartLoggerService } from '../ChartLoggerService.js';
import { name, schema } from './entities/users.js';
@ -25,14 +26,16 @@ export default class UsersChart extends Chart<typeof schema> { // eslint-disable
@Inject(DI.db)
private db: DataSource,
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
@Inject(DI.usersRepository)
private usersRepository: UsersRepository,
private appLockService: AppLockService,
private userEntityService: UserEntityService,
private chartLoggerService: ChartLoggerService,
) {
super(db, (k) => appLockService.getChartInsertLock(k), chartLoggerService.logger, name, schema);
super(db, (k) => acquireChartInsertLock(redisForTimelines, k), chartLoggerService.logger, name, schema);
}
protected async tickMajor(): Promise<Partial<KVs<typeof schema>>> {

View file

@ -20,14 +20,16 @@ import { RoleEntityService } from './RoleEntityService.js';
import type { OnModuleInit } from '@nestjs/common';
import type { UserEntityService } from './UserEntityService.js';
import type { NoteEntityService } from './NoteEntityService.js';
import type { ScheduledNoteEntityService } from './ScheduledNoteEntityService.js';
const NOTE_REQUIRED_NOTIFICATION_TYPES = new Set(['note', 'mention', 'reply', 'renote', 'renote:grouped', 'quote', 'reaction', 'reaction:grouped', 'pollEnded'] as (typeof groupedNotificationTypes[number])[]);
const NOTE_REQUIRED_NOTIFICATION_TYPES = new Set(['note', 'mention', 'reply', 'renote', 'renote:grouped', 'quote', 'reaction', 'reaction:grouped', 'pollEnded', 'scheduledNotePosted'] as (typeof groupedNotificationTypes[number])[]);
@Injectable()
export class NotificationEntityService implements OnModuleInit {
private userEntityService: UserEntityService;
private noteEntityService: NoteEntityService;
private roleEntityService: RoleEntityService;
private scheduledNoteEntityService: ScheduledNoteEntityService;
constructor(
private moduleRef: ModuleRef,
@ -52,6 +54,7 @@ export class NotificationEntityService implements OnModuleInit {
this.userEntityService = this.moduleRef.get('UserEntityService');
this.noteEntityService = this.moduleRef.get('NoteEntityService');
this.roleEntityService = this.moduleRef.get('RoleEntityService');
this.scheduledNoteEntityService = this.moduleRef.get('ScheduledNoteEntityService');
}
/**
@ -84,6 +87,11 @@ export class NotificationEntityService implements OnModuleInit {
// if the note has been deleted, don't show this notification
if (needsNote && !noteIfNeed) return null;
const needsDraft = 'draftId' in notification;
const draftIfNeed = needsDraft ? this.scheduledNoteEntityService.pack(notification.draftId, { id: meId }) : undefined;
// if the draft has been deleted, don't show this notification
if (needsDraft && !draftIfNeed) return null;
const needsUser = 'notifierId' in notification;
const userIfNeed = needsUser ? (
hint?.packedUsers != null
@ -116,6 +124,7 @@ export class NotificationEntityService implements OnModuleInit {
createdAt: new Date(notification.createdAt).toISOString(),
type: notification.type,
note: noteIfNeed,
draft: draftIfNeed,
reactions,
});
} else if (notification.type === 'renote:grouped') {
@ -139,6 +148,7 @@ export class NotificationEntityService implements OnModuleInit {
createdAt: new Date(notification.createdAt).toISOString(),
type: notification.type,
note: noteIfNeed,
draft: draftIfNeed,
users,
});
}
@ -158,6 +168,7 @@ export class NotificationEntityService implements OnModuleInit {
userId: 'notifierId' in notification ? notification.notifierId : undefined,
...(userIfNeed != null ? { user: userIfNeed } : {}),
...(noteIfNeed != null ? { note: noteIfNeed } : {}),
...(draftIfNeed != null ? { draft: draftIfNeed } : {}),
...(notification.type === 'reaction' ? {
reaction: notification.reaction,
} : {}),

View file

@ -0,0 +1,76 @@
import { Inject, Injectable } from '@nestjs/common';
import { DI } from '@/di-symbols.js';
import type { ScheduledNotesRepository } from '@/models/_.js';
import type { MiUser } from '@/models/User.js';
import type { MiScheduledNote } from '@/models/ScheduledNote.js';
import { bindThis } from '@/decorators.js';
import { Packed } from '@/misc/json-schema.js';
import { DriveFileEntityService } from './DriveFileEntityService.js';
@Injectable()
export class ScheduledNoteEntityService {
constructor(
@Inject(DI.scheduledNotesRepository)
private scheduledNotesRepository: ScheduledNotesRepository,
private driveFileEntityService: DriveFileEntityService,
) {
}
@bindThis
public async pack(
src: MiScheduledNote['id'] | MiScheduledNote,
me: { id: MiUser['id'] },
) : Promise<Packed<'NoteDraft'>> {
const item = typeof src === 'object' ? src : await this.scheduledNotesRepository.findOneByOrFail({ id: src, userId: me.id });
return {
id: item.id,
updatedAt: item.createdAt.toISOString(),
scheduledAt: item.scheduledAt?.toISOString() ?? null,
reason: item.reason ?? undefined,
channel: item.draft.channel ? {
id: item.draft.channel.id,
name: item.draft.channel.name,
} : undefined,
renote: item.draft.renote ? {
id: item.draft.renote.id,
text: (item.draft.renote.cw ?? item.draft.renote.text)?.substring(0, 100) ?? null,
user: {
id: item.draft.renote.userId,
username: item.draft.renote.user!.username,
host: item.draft.renote.user!.host,
},
} : undefined,
reply: item.draft.reply ? {
id: item.draft.reply.id,
text: (item.draft.reply.cw ?? item.draft.reply.text)?.substring(0, 100) ?? null,
user: {
id: item.draft.reply.userId,
username: item.draft.reply.user!.username,
host: item.draft.reply.user!.host,
},
} : undefined,
data: {
text: item.draft.text ?? null,
useCw: !!item.draft.cw,
cw: item.draft.cw ?? null,
visibility: item.draft.visibility as 'public' | 'followers' | 'home' | 'specified',
localOnly: item.draft.localOnly ?? false,
files: item.draft.files ? await this.driveFileEntityService.packMany(item.draft.files, me) : [],
poll: item.draft.poll ? { ...item.draft.poll, expiresAt: item.draft.poll.expiresAt?.getTime() ?? null, expiredAfter: null } : null,
visibleUserIds: item.draft.visibility === 'specified' ? item.draft.visibleUsers?.map(x => x.id) : undefined,
},
};
}
@bindThis
public async packMany(
drafts: (MiScheduledNote['id'] | MiScheduledNote)[],
me: { id: MiUser['id'] },
) : Promise<Packed<'NoteDraft'>[]> {
return (await Promise.allSettled(drafts.map(x => this.pack(x, me))))
.filter(result => result.status === 'fulfilled')
.map(result => (result as PromiseFulfilledResult<Packed<'NoteDraft'>>).value);
}
}

View file

@ -489,6 +489,7 @@ export class UserEntityService implements OnModuleInit {
}))) : [],
isBot: user.isBot,
isCat: user.isCat,
speakAsCat: user.speakAsCat,
instance: user.host ? this.federatedInstanceService.federatedInstanceCache.fetch(user.host).then(instance => instance ? {
name: instance.name,
softwareName: instance.softwareName,

View file

@ -21,6 +21,7 @@ export const DI = {
announcementReadsRepository: Symbol('announcementReadsRepository'),
appsRepository: Symbol('appsRepository'),
avatarDecorationsRepository: Symbol('avatarDecorationsRepository'),
scheduledNotesRepository: Symbol('scheduledNotesRepository'),
noteFavoritesRepository: Symbol('noteFavoritesRepository'),
noteThreadMutingsRepository: Symbol('noteThreadMutingsRepository'),
noteReactionsRepository: Symbol('noteReactionsRepository'),

View file

@ -0,0 +1,44 @@
import * as Redis from 'ioredis';
export async function acquireDistributedLock(
redis: Redis.Redis,
name: string,
timeout: number,
maxRetries: number,
retryInterval: number,
): Promise<() => Promise<void>> {
const lockKey = `lock:${name}`;
const identifier = Math.random().toString(36).slice(2);
let retries = 0;
while (retries < maxRetries) {
const result = await redis.set(lockKey, identifier, 'PX', timeout, 'NX');
if (result === 'OK') {
return async () => {
const currentIdentifier = await redis.get(lockKey);
if (currentIdentifier === identifier) {
await redis.del(lockKey);
}
};
}
await new Promise(resolve => setTimeout(resolve, retryInterval));
retries++;
}
throw new Error(`Failed to acquire lock ${name}`);
}
export function acquireApObjectLock(
redis: Redis.Redis,
uri: string,
): Promise<() => Promise<void>> {
return acquireDistributedLock(redis, `ap-object:${uri}`, 30 * 1000, 600, 100);
}
export function acquireChartInsertLock(
redis: Redis.Redis,
name: string,
): Promise<() => Promise<void>> {
return acquireDistributedLock(redis, `chart-insert:${name}`, 30 * 1000, 120, 500);
}

View file

@ -31,6 +31,7 @@ import { packedMutingSchema } from '@/models/json-schema/muting.js';
import { packedNoteFavoriteSchema } from '@/models/json-schema/note-favorite.js';
import { packedNoteReactionSchema } from '@/models/json-schema/note-reaction.js';
import { packedNoteSchema } from '@/models/json-schema/note.js';
import { packedNoteDraftSchema } from '@/models/json-schema/note-draft.js';
import { packedNotificationSchema } from '@/models/json-schema/notification.js';
import { packedPageLikeSchema, packedPageBlockSchema, packedPageSchema } from '@/models/json-schema/page.js';
import { packedQueueCountSchema } from '@/models/json-schema/queue.js';
@ -77,6 +78,7 @@ export const refs = {
Announcement: packedAnnouncementSchema,
App: packedAppSchema,
Note: packedNoteSchema,
NoteDraft: packedNoteDraftSchema,
NoteReaction: packedNoteReactionSchema,
NoteFavorite: packedNoteFavoriteSchema,
Notification: packedNotificationSchema,

View file

@ -0,0 +1,42 @@
import { permissions } from 'misskey-js';
const mastodonToMisskeyScopes: Map<string, (typeof permissions)[number][]> = new Map([
['profile', ['read:account']],
['follow', ['read:following', 'write:following', 'read:blocks', 'write:blocks', 'read:mutes', 'write:mutes']],
['push', ['write:push-notification']],
['read:accounts', ['read:account']],
['read:blocks', ['read:blocks']],
['read:bookmarks', ['read:favorites']],
['read:favourites', ['read:reactions']],
['read:filters', ['read:account']],
['read:follows', ['read:following']],
['read:lists', ['read:account']],
['read:mutes', ['read:mutes']],
['read:notifications', ['read:notifications']],
['read:search', []],
['read:statuses', []],
['write:accounts', ['write:account']],
['write:blocks', ['write:blocks']],
['write:bookmarks', ['write:favorites']],
['write:conversations', ['write:notes']],
['write:favourites', ['write:reactions']],
['write:filters', ['write:account']],
['write:follows', ['write:following']],
['write:lists', ['write:account']],
['write:media', ['read:drive', 'write:drive']],
['write:mutes', ['write:mutes']],
['write:notifications', ['write:notifications']],
['write:reports', ['write:report-abuse']],
['write:statuses', ['write:notes']],
]);
function setHighLevelScope(scopeName: string) {
const granularScopes = Array.from(mastodonToMisskeyScopes)
.flatMap(([key, value]) => key.startsWith(scopeName + ':') ? value : []);
mastodonToMisskeyScopes.set(scopeName, Array.from(new Set(granularScopes)));
}
setHighLevelScope('read');
setHighLevelScope('write');
export { mastodonToMisskeyScopes };

View file

@ -63,4 +63,22 @@ export class MiApp {
comment: 'The callbackUrl of the App.',
})
public callbackUrl: string | null;
@Column('varchar', {
length: 128, nullable: true,
comment: 'Application website.',
})
public website: string;
@Column('varchar', {
length: 64, array: true, nullable: true,
comment: 'Mastodon app scopes, only set for apps created with Mastodon API.',
})
public mastodonScopes: string[];
@Column('varchar', {
length: 512, array: true, nullable: true,
comment: 'Redirect URIs.',
})
public redirectUris: string[];
}

View file

@ -5,6 +5,7 @@
import { MiUser } from './User.js';
import { MiNote } from './Note.js';
import { MiScheduledNote } from './ScheduledNote.js';
import { MiAccessToken } from './AccessToken.js';
import { MiRole } from './Role.js';
@ -77,6 +78,21 @@ export type MiNotification = {
id: string;
createdAt: string;
achievement: string;
} | {
type: 'noteScheduled';
id: string;
createdAt: string;
draftId: MiScheduledNote['id'];
} | {
type: 'scheduledNotePosted';
id: string;
createdAt: string;
noteId: MiNote['id'];
} | {
type: 'scheduledNoteError';
id: string;
createdAt: string;
draftId: MiScheduledNote['id'];
} | {
type: 'app';
id: string;

View file

@ -39,6 +39,7 @@ import {
MiModerationLog,
MiMuting,
MiNote,
MiScheduledNote,
MiNoteFavorite,
MiNoteReaction,
MiNoteThreadMuting,
@ -117,6 +118,12 @@ const $avatarDecorationsRepository: Provider = {
inject: [DI.db],
};
const $scheduledNotesRepository: Provider = {
provide: DI.scheduledNotesRepository,
useFactory: (db: DataSource) => db.getRepository(MiScheduledNote),
inject: [DI.db],
};
const $noteFavoritesRepository: Provider = {
provide: DI.noteFavoritesRepository,
useFactory: (db: DataSource) => db.getRepository(MiNoteFavorite),
@ -517,6 +524,7 @@ const $abuseReportResolversRepository: Provider = {
$announcementReadsRepository,
$appsRepository,
$avatarDecorationsRepository,
$scheduledNotesRepository,
$noteFavoritesRepository,
$noteThreadMutingsRepository,
$noteReactionsRepository,
@ -590,6 +598,7 @@ const $abuseReportResolversRepository: Provider = {
$announcementReadsRepository,
$appsRepository,
$avatarDecorationsRepository,
$scheduledNotesRepository,
$noteFavoritesRepository,
$noteThreadMutingsRepository,
$noteReactionsRepository,

View file

@ -0,0 +1,54 @@
import { Entity, Index, JoinColumn, Column, PrimaryColumn, ManyToOne } from 'typeorm';
import type { NoteCreateOption } from '@/types.js';
import { id } from './util/id.js';
import { MiUser } from './User.js';
@Entity('note_scheduled')
@Index(['userId', 'scheduledAt'], { unique: true })
export class MiScheduledNote {
@PrimaryColumn(id())
public id: string;
@Index()
@Column('timestamp with time zone', {
comment: 'The created date of the Note.',
default: () => 'CURRENT_TIMESTAMP',
})
public createdAt: Date;
@Index()
@Column('timestamp with time zone', {
comment: 'The scheduled date of the Note.',
nullable: true
})
public scheduledAt: Date | null;
@Column('varchar', {
length: 256, nullable: true,
})
public reason: string | null;
@Index()
@Column({
...id(),
comment: 'The ID of author.',
})
public userId: MiUser['id'];
@ManyToOne(type => MiUser, {
onDelete: 'CASCADE',
})
@JoinColumn()
public user: MiUser | null;
@Column('jsonb')
public draft: NoteCreateOption;
constructor(data: Partial<MiScheduledNote>) {
if (data == null) return;
for (const [k, v] of Object.entries(data)) {
(this as any)[k] = v;
}
}
}

View file

@ -186,6 +186,12 @@ export class MiUser {
})
public isCat: boolean;
@Column('boolean', {
default: false,
comment: 'Whether the User speaks in nya.',
})
public speakAsCat: boolean;
@Column('boolean', {
default: false,
comment: 'Whether the User is the root.',

View file

@ -34,6 +34,7 @@ import { MiModerationLog } from '@/models/ModerationLog.js';
import { MiMuting } from '@/models/Muting.js';
import { MiRenoteMuting } from '@/models/RenoteMuting.js';
import { MiNote } from '@/models/Note.js';
import { MiScheduledNote } from '@/models/ScheduledNote.js';
import { MiNoteFavorite } from '@/models/NoteFavorite.js';
import { MiNoteReaction } from '@/models/NoteReaction.js';
import { MiNoteThreadMuting } from '@/models/NoteThreadMuting.js';
@ -108,6 +109,7 @@ export {
MiMuting,
MiRenoteMuting,
MiNote,
MiScheduledNote,
MiNoteFavorite,
MiNoteReaction,
MiNoteThreadMuting,
@ -181,6 +183,7 @@ export type ModerationLogsRepository = Repository<MiModerationLog>;
export type MutingsRepository = Repository<MiMuting>;
export type RenoteMutingsRepository = Repository<MiRenoteMuting>;
export type NotesRepository = Repository<MiNote>;
export type ScheduledNotesRepository = Repository<MiScheduledNote>;
export type NoteFavoritesRepository = Repository<MiNoteFavorite>;
export type NoteReactionsRepository = Repository<MiNoteReaction>;
export type NoteThreadMutingsRepository = Repository<MiNoteThreadMuting>;

View file

@ -0,0 +1,179 @@
export const packedNoteDraftSchema = {
type: 'object',
properties: {
id: {
type: 'string',
optional: false, nullable: false,
format: 'misskey:id'
},
updatedAt: {
type: 'string',
optional: false, nullable: false,
format: 'date-time'
},
scheduledAt: {
type: 'string',
optional: false, nullable: true,
format: 'date-time',
},
reason: {
type: 'string',
optional: true, nullable: false
},
channel: {
type: 'object',
optional: true, nullable: true,
properties: {
id: {
type: 'string',
optional: false, nullable: false,
format: 'misskey:id'
},
name: {
type: 'string',
optional: false, nullable: false
},
},
},
renote: {
type: 'object',
optional: true, nullable: true,
properties: {
id: {
type: 'string',
optional: false, nullable: false,
format: 'misskey:id',
},
text: {
type: 'string',
optional: false, nullable: true,
},
user: {
type: 'object',
optional: false, nullable: false,
properties: {
id: {
type: 'string',
optional: false, nullable: false,
format: 'misskey:id',
},
username: {
type: 'string',
optional: false, nullable: false,
},
host: {
type: 'string',
optional: false, nullable: true,
},
},
},
},
},
reply: {
type: 'object',
optional: true, nullable: true,
properties: {
id: {
type: 'string',
optional: false, nullable: false,
format: 'misskey:id',
},
text: {
type: 'string',
optional: false, nullable: true,
},
user: {
type: 'object',
optional: false, nullable: false,
properties: {
id: {
type: 'string',
optional: false, nullable: false,
format: 'misskey:id'
},
username: {
type: 'string',
optional: false, nullable: false,
},
host: {
type: 'string',
optional: false, nullable: true,
},
},
},
},
},
data: {
type: 'object',
optional: false, nullable: false,
properties: {
text: {
type: 'string',
optional: false, nullable: true,
},
useCw: {
type: 'boolean',
optional: false, nullable: false,
},
cw: {
type: 'string',
optional: false, nullable: true,
},
visibility: {
type: 'string',
optional: false, nullable: false,
enum: ['public', 'home', 'followers', 'specified'],
},
localOnly: {
type: 'boolean',
optional: false, nullable: false,
},
files: {
type: 'array',
optional: false, nullable: false,
items: {
type: 'object',
optional: false, nullable: false,
ref: 'DriveFile',
},
},
poll: {
type: 'object',
optional: false, nullable: true,
properties: {
choices: {
type: 'array',
optional: false, nullable: false,
items: {
type: 'string',
optional: false, nullable: false,
},
},
multiple: {
type: 'boolean',
optional: false, nullable: false,
},
expiresAt: {
type: 'integer',
optional: false, nullable: true,
},
expiredAfter: {
type: 'integer',
optional: false, nullable: true,
minimum: 1
},
},
},
visibleUserIds: {
type: 'array',
optional: true, nullable: false,
items: {
type: 'string',
optional: false, nullable: false,
format: 'misskey:id',
},
},
},
},
},
} as const;

View file

@ -296,6 +296,51 @@ export const packedNotificationSchema = {
optional: false, nullable: false,
},
},
}, {
type: 'object',
properties: {
...baseSchema.properties,
type: {
type: 'string',
optional: false, nullable: false,
enum: ['noteScheduled'],
},
draft: {
type: 'object',
ref: 'NoteDraft',
optional: false, nullable: false,
}
}
}, {
type: 'object',
properties: {
...baseSchema.properties,
type: {
type: 'string',
optional: false, nullable: false,
enum: ['scheduledNotePosted'],
},
note: {
type: 'object',
ref: 'Note',
optional: false, nullable: false,
}
}
}, {
type: 'object',
properties: {
...baseSchema.properties,
type: {
type: 'string',
optional: false, nullable: false,
enum: ['scheduledNoteError'],
},
draft: {
type: 'object',
ref: 'NoteDraft',
optional: false, nullable: false,
}
}
}, {
type: 'object',
properties: {

View file

@ -180,6 +180,18 @@ export const packedRolePoliciesSchema = {
type: 'boolean',
optional: false, nullable: false,
},
canScheduleNote: {
type: 'boolean',
optional: false, nullable: false,
},
scheduleNoteLimit: {
type: 'integer',
optional: false, nullable: false,
},
scheduleNoteMaxDays: {
type: 'integer',
optional: false, nullable: false,
},
canInitiateConversation: {
type: 'boolean',
optional: false, nullable: false,

View file

@ -115,6 +115,10 @@ export const packedUserLiteSchema = {
type: 'boolean',
nullable: false, optional: true,
},
speakAsCat: {
type: 'boolean',
nullable: false, optional: true,
},
instance: {
type: 'object',
nullable: false, optional: true,

View file

@ -44,6 +44,7 @@ import { MiModerationLog } from '@/models/ModerationLog.js';
import { MiMuting } from '@/models/Muting.js';
import { MiRenoteMuting } from '@/models/RenoteMuting.js';
import { MiNote } from '@/models/Note.js';
import { MiScheduledNote } from '@/models/ScheduledNote.js';
import { MiNoteFavorite } from '@/models/NoteFavorite.js';
import { MiNoteReaction } from '@/models/NoteReaction.js';
import { MiNoteThreadMuting } from '@/models/NoteThreadMuting.js';
@ -162,6 +163,7 @@ export const entities = [
MiRenoteMuting,
MiBlocking,
MiNote,
MiScheduledNote,
MiNoteFavorite,
MiNoteReaction,
MiNoteThreadMuting,

View file

@ -13,6 +13,7 @@ import { EndedPollNotificationProcessorService } from './processors/EndedPollNot
import { InboxProcessorService } from './processors/InboxProcessorService.js';
import { WebhookDeliverProcessorService } from './processors/WebhookDeliverProcessorService.js';
import { CheckExpiredMutingsProcessorService } from './processors/CheckExpiredMutingsProcessorService.js';
import { CheckMissingScheduledNoteProcessorService } from './processors/CheckMissingScheduledNoteProcessorService.js';
import { CleanChartsProcessorService } from './processors/CleanChartsProcessorService.js';
import { CleanProcessorService } from './processors/CleanProcessorService.js';
import { CleanRemoteFilesProcessorService } from './processors/CleanRemoteFilesProcessorService.js';
@ -36,6 +37,7 @@ import { ImportUserListsProcessorService } from './processors/ImportUserListsPro
import { ImportAntennasProcessorService } from './processors/ImportAntennasProcessorService.js';
import { ResyncChartsProcessorService } from './processors/ResyncChartsProcessorService.js';
import { ReportAbuseProcessorService } from './processors/ReportAbuseProcessorService.js';
import { ScheduledNoteProcessorService } from './processors/ScheduledNoteProcessorService.js';
import { TickChartsProcessorService } from './processors/TickChartsProcessorService.js';
import { AggregateRetentionProcessorService } from './processors/AggregateRetentionProcessorService.js';
import { ExportFavoritesProcessorService } from './processors/ExportFavoritesProcessorService.js';
@ -52,6 +54,7 @@ import { RelationshipProcessorService } from './processors/RelationshipProcessor
ResyncChartsProcessorService,
CleanChartsProcessorService,
CheckExpiredMutingsProcessorService,
CheckMissingScheduledNoteProcessorService,
CleanProcessorService,
DeleteDriveFilesProcessorService,
ExportCustomEmojisProcessorService,
@ -75,6 +78,7 @@ import { RelationshipProcessorService } from './processors/RelationshipProcessor
CleanRemoteFilesProcessorService,
RelationshipProcessorService,
ReportAbuseProcessorService,
ScheduledNoteProcessorService,
WebhookDeliverProcessorService,
EndedPollNotificationProcessorService,
DeliverProcessorService,

View file

@ -35,10 +35,12 @@ import { CleanRemoteFilesProcessorService } from './processors/CleanRemoteFilesP
import { DeleteFileProcessorService } from './processors/DeleteFileProcessorService.js';
import { RelationshipProcessorService } from './processors/RelationshipProcessorService.js';
import { ReportAbuseProcessorService } from './processors/ReportAbuseProcessorService.js';
import { TickChartsProcessorService } from './processors/TickChartsProcessorService.js';
import { ResyncChartsProcessorService } from './processors/ResyncChartsProcessorService.js';
import { ScheduledNoteProcessorService } from './processors/ScheduledNoteProcessorService.js';
import { TickChartsProcessorService } from './processors/TickChartsProcessorService.js';
import { CleanChartsProcessorService } from './processors/CleanChartsProcessorService.js';
import { CheckExpiredMutingsProcessorService } from './processors/CheckExpiredMutingsProcessorService.js';
import { CheckMissingScheduledNoteProcessorService } from './processors/CheckMissingScheduledNoteProcessorService.js';
import { CleanProcessorService } from './processors/CleanProcessorService.js';
import { AggregateRetentionProcessorService } from './processors/AggregateRetentionProcessorService.js';
import { QueueLoggerService } from './QueueLoggerService.js';
@ -113,11 +115,13 @@ export class QueueProcessorService implements OnApplicationShutdown {
private cleanRemoteFilesProcessorService: CleanRemoteFilesProcessorService,
private relationshipProcessorService: RelationshipProcessorService,
private reportAbuseProcessorService: ReportAbuseProcessorService,
private tickChartsProcessorService: TickChartsProcessorService,
private resyncChartsProcessorService: ResyncChartsProcessorService,
private scheduledNoteProcessorService: ScheduledNoteProcessorService,
private tickChartsProcessorService: TickChartsProcessorService,
private cleanChartsProcessorService: CleanChartsProcessorService,
private aggregateRetentionProcessorService: AggregateRetentionProcessorService,
private checkExpiredMutingsProcessorService: CheckExpiredMutingsProcessorService,
private checkMissingScheduledNoteProcessorService: CheckMissingScheduledNoteProcessorService,
private cleanProcessorService: CleanProcessorService,
) {
this.logger = this.queueLoggerService.logger;
@ -141,11 +145,13 @@ export class QueueProcessorService implements OnApplicationShutdown {
//#region system
this.systemQueueWorker = new Bull.Worker(QUEUE.SYSTEM, (job) => {
switch (job.name) {
case 'scheduledNote': return this.scheduledNoteProcessorService.process(job);
case 'tickCharts': return this.tickChartsProcessorService.process();
case 'resyncCharts': return this.resyncChartsProcessorService.process();
case 'cleanCharts': return this.cleanChartsProcessorService.process();
case 'aggregateRetention': return this.aggregateRetentionProcessorService.process();
case 'checkExpiredMutings': return this.checkExpiredMutingsProcessorService.process();
case 'checkMissingScheduledNote': return this.checkMissingScheduledNoteProcessorService.process();
case 'clean': return this.cleanProcessorService.process();
default: throw new Error(`unrecognized job type ${job.name} for system`);
}

View file

@ -0,0 +1,61 @@
import { Inject, Injectable } from '@nestjs/common';
import * as Redis from 'ioredis';
import { DI } from '@/di-symbols.js';
import type { ScheduledNotesRepository } from '@/models/_.js';
import type Logger from '@/logger.js';
import { bindThis } from '@/decorators.js';
import { acquireDistributedLock } from '@/misc/distributed-lock.js';
import { QueueService } from '@/core/QueueService.js';
import { QueueLoggerService } from '../QueueLoggerService.js';
@Injectable()
export class CheckMissingScheduledNoteProcessorService {
private logger: Logger;
constructor(
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
@Inject(DI.scheduledNotesRepository)
private scheduledNotesRepository: ScheduledNotesRepository,
private queueService: QueueService,
private queueLoggerService: QueueLoggerService,
) {
this.logger = this.queueLoggerService.logger.createSubLogger('note:scheduled');
}
@bindThis
public async process(): Promise<void> {
this.logger.info(`checking missing scheduled note tasks`);
try {
await acquireDistributedLock(this.redisForTimelines, `note:scheduled:check`, 3 * 60 * 1000, 1, 1000);
} catch (e) {
this.logger.warn(`check is already being processed`);
return;
}
const query = this.scheduledNotesRepository.createQueryBuilder('draft')
.where('draft.scheduledAt < now() + interval \'10 minutes\'').orderBy('draft.createdAt', 'ASC');
let lastId = '0';
while (true) {
const drafts = await query.andWhere('draft.id > :lastId', { lastId }).limit(100).getMany();
if (drafts.length === 0) {
break;
}
for (const draft of drafts.filter(draft => draft.scheduledAt !== null)) {
const jobState = await this.queueService.systemQueue.getJobState(`scheduledNote:${draft.id}`);
if (jobState !== 'unknown') continue;
this.logger.warn(`found missing scheduled note task: ${draft.id}`);
await this.queueService.createScheduledNoteJob(draft.id, draft.scheduledAt!);
}
lastId = drafts[drafts.length - 1].id;
}
}
}

View file

@ -0,0 +1,101 @@
import { Inject, Injectable } from '@nestjs/common';
import { IsNull } from 'typeorm';
import * as Bull from 'bullmq';
import * as Redis from 'ioredis';
import { DI } from '@/di-symbols.js';
import { MiNote, type ScheduledNotesRepository } from '@/models/_.js';
import type Logger from '@/logger.js';
import { bindThis } from '@/decorators.js';
import { IdentifiableError } from '@/misc/identifiable-error.js';
import { acquireDistributedLock } from '@/misc/distributed-lock.js';
import { NotificationService } from '@/core/NotificationService.js';
import { NoteCreateService } from '@/core/NoteCreateService.js';
import { QueueLoggerService } from '../QueueLoggerService.js';
import type { ScheduledNoteJobData } from '../types.js';
@Injectable()
export class ScheduledNoteProcessorService {
private logger: Logger;
constructor(
@Inject(DI.redisForTimelines)
private redisForTimelines: Redis.Redis,
@Inject(DI.scheduledNotesRepository)
private scheduledNotesRepository: ScheduledNotesRepository,
private notificationService: NotificationService,
private noteCreateService: NoteCreateService,
private queueLoggerService: QueueLoggerService,
) {
this.logger = this.queueLoggerService.logger.createSubLogger('note:scheduled');
}
@bindThis
public async process(job: Bull.Job<ScheduledNoteJobData>): Promise<string> {
this.logger.info(`processing ${job.data.draftId}`);
try {
await acquireDistributedLock(this.redisForTimelines, `note:scheduled:${job.data.draftId}`, 30 * 1000, 1, 100);
} catch (e) {
this.logger.warn(`draft=${job.data.draftId} is already being processed`);
return 'ok';
}
const draft = await this.scheduledNotesRepository.findOne({
where: { id: job.data.draftId, reason: IsNull() },
relations: ['user'],
});
if (draft == null) {
this.logger.warn(`draft not found: ${job.data.draftId}`);
return 'ok';
}
if (!draft.user || draft.user.isSuspended) {
this.logger.warn(`user is suspended: ${draft.userId}`);
await this.scheduledNotesRepository.delete({ id: draft.id });
return 'ok';
}
try {
const note = (await this.noteCreateService.create(draft.user, {
...draft.draft,
createdAt: new Date(),
scheduledAt: null,
})) as MiNote;
await this.scheduledNotesRepository.delete({ id: draft.id });
this.notificationService.createNotification(draft.userId, "scheduledNotePosted", {
noteId: note.id,
});
return 'ok';
} catch (e) {
if (e instanceof IdentifiableError) {
if ([
'e11b3a16-f543-4885-8eb1-66cad131dbfd',
'689ee33f-f97c-479a-ac49-1b9f8140af99',
'9f466dab-c856-48cd-9e65-ff90ff750580',
'85ab9bd7-3a41-4530-959d-f07073900109',
'd450b8a9-48e4-4dab-ae36-f4db763fda7c',
].includes(e.id)) {
this.logger.warn(`creating note from draft=${draft.id} failed: ${e.message}`);
await this.scheduledNotesRepository.update({ id: draft.id }, {
scheduledAt: null,
reason: e.message,
});
this.notificationService.createNotification(draft.userId, "scheduledNoteError", {
draftId: draft.id,
});
return e.message;
}
}
throw e;
}
}
}

View file

@ -6,6 +6,7 @@
import type { Antenna } from '@/server/api/endpoints/i/import-antennas.js';
import type { MiDriveFile } from '@/models/DriveFile.js';
import type { MiNote } from '@/models/Note.js';
import type { MiScheduledNote } from '@/models/ScheduledNote.js';
import type { MiUser } from '@/models/User.js';
import type { MiAbuseUserReport } from '@/models/AbuseUserReport.js';
import type { MiWebhook } from '@/models/Webhook.js';
@ -116,6 +117,10 @@ export type EndedPollNotificationJobData = {
noteId: MiNote['id'];
};
export type ScheduledNoteJobData = {
draftId: MiScheduledNote['id'];
};
export type WebhookDeliverJobData = {
type: string;
content: unknown;

View file

@ -7,6 +7,7 @@ import { Inject, Injectable } from '@nestjs/common';
import cors from '@fastify/cors';
import multipart from '@fastify/multipart';
import fastifyCookie from '@fastify/cookie';
import fastifyFormbody from '@fastify/formbody';
import { ModuleRef } from '@nestjs/core';
import type { Config } from '@/config.js';
import type { InstancesRepository, AccessTokensRepository } from '@/models/_.js';
@ -63,6 +64,13 @@ export class ApiServerService {
done();
});
fastify.register(this.createMisskeyServer);
fastify.register(this.createMastodonServer);
done();
}
@bindThis
private createMisskeyServer(fastify: FastifyInstance, options: FastifyPluginOptions, done: (err?: Error) => void) {
for (const endpoint of endpoints) {
const ep = {
name: endpoint.name,
@ -106,32 +114,6 @@ export class ApiServerService {
}
}
const createEndpoint = (endpoint: IMastodonEndpoint): IMastodonEndpoint & { exec: any } => ({
name: endpoint.name,
method: endpoint.method,
meta: endpoint.meta,
params: endpoint.params,
exec: this.moduleRef.get(`mep:${endpoint.method}:${endpoint.name}`, { strict: false }).exec,
});
const groupedMastodonEndpoints = Array.from(Map.groupBy(mastodonEndpoints.map(createEndpoint), endpoint => endpoint.name))
.map(([name, endpoints]) => ({ name, endpoints: new Map(endpoints.map(endpoint => [endpoint.method, endpoint])) }));
for (const { name, endpoints } of groupedMastodonEndpoints) {
fastify.all<{
Params: { endpoint: string; },
Body: Record<string, unknown>,
Querystring: Record<string, unknown>,
}>('/' + name, async (request, reply) => {
const ep = endpoints.get(request.method);
if (!ep) {
reply.code(405);
reply.send();
return;
}
await this.apiCallService.handleMastodonRequest(ep, request, reply);
return reply;
});
}
fastify.post<{
Body: {
username: string;
@ -212,4 +194,39 @@ export class ApiServerService {
done();
}
@bindThis
private createMastodonServer(fastify: FastifyInstance, options: FastifyPluginOptions, done: (err?: Error) => void) {
fastify.register(fastifyFormbody);
const createEndpoint = (endpoint: IMastodonEndpoint): IMastodonEndpoint & { exec: any } => ({
name: endpoint.name,
method: endpoint.method,
meta: endpoint.meta,
params: endpoint.params,
exec: this.moduleRef.get(`mep:${endpoint.method}:${endpoint.name}`, { strict: false }).exec,
});
const groupedMastodonEndpoints = Array.from(Map.groupBy(mastodonEndpoints.map(createEndpoint), endpoint => endpoint.name))
.map(([name, endpoints]) => ({ name, endpoints: new Map(endpoints.map(endpoint => [endpoint.method, endpoint])) }));
for (const { name, endpoints } of groupedMastodonEndpoints) {
fastify.all<{
Params: { endpoint: string; },
Body: Record<string, unknown>,
Querystring: Record<string, unknown>,
}>('/' + name, async (request, reply) => {
const ep = endpoints.get(request.method);
if (!ep) {
reply.code(405);
reply.send();
return;
}
await this.apiCallService.handleMastodonRequest(ep, request, reply);
return reply;
});
}
done();
}
}

View file

@ -289,6 +289,8 @@ 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_scheduled_cancel from './endpoints/notes/scheduled/cancel.js';
import * as ep___notes_scheduled_list from './endpoints/notes/scheduled/list.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';
@ -686,6 +688,8 @@ const $notes_clips: Provider = { provide: 'ep:notes/clips', useClass: ep___notes
const $notes_conversation: Provider = { provide: 'ep:notes/conversation', useClass: ep___notes_conversation.default };
const $notes_create: Provider = { provide: 'ep:notes/create', useClass: ep___notes_create.default };
const $notes_delete: Provider = { provide: 'ep:notes/delete', useClass: ep___notes_delete.default };
const $notes_scheduled_cancel: Provider = { provide: 'ep:notes/scheduled/cancel', useClass: ep___notes_scheduled_cancel.default };
const $notes_scheduled_list: Provider = { provide: 'ep:notes/scheduled/list', useClass: ep___notes_scheduled_list.default };
const $notes_favorites_create: Provider = { provide: 'ep:notes/favorites/create', useClass: ep___notes_favorites_create.default };
const $notes_favorites_delete: Provider = { provide: 'ep:notes/favorites/delete', useClass: ep___notes_favorites_delete.default };
const $notes_featured: Provider = { provide: 'ep:notes/featured', useClass: ep___notes_featured.default };
@ -1087,6 +1091,8 @@ const $reversi_verify: Provider = { provide: 'ep:reversi/verify', useClass: ep__
$notes_conversation,
$notes_create,
$notes_delete,
$notes_scheduled_cancel,
$notes_scheduled_list,
$notes_favorites_create,
$notes_favorites_delete,
$notes_featured,
@ -1481,6 +1487,8 @@ const $reversi_verify: Provider = { provide: 'ep:reversi/verify', useClass: ep__
$notes_conversation,
$notes_create,
$notes_delete,
$notes_scheduled_cancel,
$notes_scheduled_list,
$notes_favorites_create,
$notes_favorites_delete,
$notes_featured,

View file

@ -2,8 +2,10 @@ import { Module, Provider } from '@nestjs/common';
import { CoreModule } from '@/core/CoreModule.js';
import * as mep___accounts_lookup_v1_get from './mastodon/accounts/lookup/v1/get.js';
import * as mep___apps_v1_post from './mastodon/apps/v1/post.js';
const $accounts_lookup_v1_get: Provider = { provide: 'mep:GET:v1/accounts/lookup', useClass: mep___accounts_lookup_v1_get.default };
const $apps_v1_post: Provider = { provide: 'mep:POST:v1/apps', useClass: mep___apps_v1_post.default };
@Module({
imports: [
@ -11,9 +13,11 @@ const $accounts_lookup_v1_get: Provider = { provide: 'mep:GET:v1/accounts/lookup
],
providers: [
$accounts_lookup_v1_get,
$apps_v1_post,
],
exports: [
$accounts_lookup_v1_get,
$apps_v1_post,
],
})
export class MastodonEndpointsModule {}

View file

@ -99,10 +99,15 @@ export class SigninApiService {
reply.code(429);
return {
error: {
message: 'Too many failed attempts to sign in. Try again later.',
code: 'TOO_MANY_AUTHENTICATION_FAILURES',
message: 'Rate limit exceeded. Please try again later.',
code: 'RATE_LIMIT_EXCEEDED',
id: '22d05606-fbcf-421a-a2db-b32610dcfd1b',
},
info: {
message: 'Too many failed attempts to sign in.',
code: 'TOO_MANY_AUTHENTICATION_FAILURES',
id: '6c181469-ecb9-42d2-82c9-60db5486a819',
},
}
};
}

View file

@ -289,6 +289,8 @@ 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_scheduled_cancel from './endpoints/notes/scheduled/cancel.js';
import * as ep___notes_scheduled_list from './endpoints/notes/scheduled/list.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';
@ -684,6 +686,8 @@ const eps = [
['notes/conversation', ep___notes_conversation],
['notes/create', ep___notes_create],
['notes/delete', ep___notes_delete],
['notes/scheduled/cancel', ep___notes_scheduled_cancel],
['notes/scheduled/list', ep___notes_scheduled_list],
['notes/favorites/create', ep___notes_favorites_create],
['notes/favorites/delete', ep___notes_favorites_delete],
['notes/featured', ep___notes_featured],

View file

@ -187,6 +187,7 @@ export const paramDef = {
preventAiLearning: { type: 'boolean' },
isBot: { type: 'boolean' },
isCat: { type: 'boolean' },
speakAsCat: { type: 'boolean' },
injectFeaturedNote: { type: 'boolean' },
receiveAnnouncementEmail: { type: 'boolean' },
alwaysMarkNsfw: { type: 'boolean' },
@ -341,6 +342,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
if (typeof ps.noCrawle === 'boolean') profileUpdates.noCrawle = ps.noCrawle;
if (typeof ps.preventAiLearning === 'boolean') profileUpdates.preventAiLearning = ps.preventAiLearning;
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') {

View file

@ -17,6 +17,7 @@ import { MAX_NOTE_TEXT_LENGTH } from '@/const.js';
import { Endpoint } from '@/server/api/endpoint-base.js';
import { NoteEntityService } from '@/core/entities/NoteEntityService.js';
import { NoteCreateService } from '@/core/NoteCreateService.js';
import { NotificationService } from '@/core/NotificationService.js';
import { DI } from '@/di-symbols.js';
import { isQuote, isRenote } from '@/misc/is-renote.js';
import { IdentifiableError } from '@/misc/identifiable-error.js';
@ -148,6 +149,39 @@ export const meta = {
id: '66819f28-9525-389d-4b0a-4974363fbbbf',
},
cannotScheduleToPast: {
message: 'Cannot schedule to the past.',
code: 'CANNOT_SCHEDULE_TO_PAST',
id: 'e577d185-8179-4a17-b47f-6093985558e6',
},
cannotScheduleSameTime: {
message: 'Cannot schedule multiple notes at the same time.',
code: 'CANNOT_SCHEDULE_SAME_TIME',
id: '187a8fab-fd83-4ae6-a46c-0f6f07784634',
},
tooManyScheduledNotes: {
message: 'You cannot schedule notes any more.',
code: 'TOO_MANY_SCHEDULED_NOTES',
kind: 'permission',
id: '9e33041f-f6fb-414d-98c1-591466e55287'
},
cannotScheduleToFarFuture: {
message: 'Cannot schedule to the far future.',
code: 'CANNOT_SCHEDULE_TO_FAR_FUTURE',
kind: 'permission',
id: 'ea102856-e8da-4ae9-a98a-0326821bd177',
},
rolePermissionDenied: {
message: 'You are not assigned to a required role.',
code: 'ROLE_PERMISSION_DENIED',
kind: 'permission',
id: '12f1d5d2-f7ec-4d7c-b608-e873f4b20327',
status: 403,
},
},
} as const;
@ -207,6 +241,7 @@ export const paramDef = {
},
required: ['choices'],
},
scheduledAt: { type: 'integer', nullable: true },
noCreatedNote: { type: 'boolean', default: false },
},
// (re)note with text, files and poll are optional
@ -263,6 +298,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
private loggerService: LoggerService,
private noteEntityService: NoteEntityService,
private noteCreateService: NoteCreateService,
private notificationService: NotificationService,
) {
super(meta, paramDef, async (ps, me, _token, _file, _cleanup, ip, headers) => {
const logger = this.loggerService.getLogger('api:notes:create');
@ -318,7 +354,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
let renote: MiNote | null = null;
if (ps.renoteId != null) {
// Fetch renote to note
renote = await this.notesRepository.findOneBy({ id: ps.renoteId });
renote = await this.notesRepository.findOne({ where: { id: ps.renoteId }, relations: ['user'] });
if (renote == null) {
logger.error('No such renote target.', { renoteId: ps.renoteId });
@ -371,7 +407,7 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
let reply: MiNote | null = null;
if (ps.replyId != null) {
// Fetch reply
reply = await this.notesRepository.findOneBy({ id: ps.replyId });
reply = await this.notesRepository.findOne({ where: { id: ps.replyId }, relations: ['user'] });
if (reply == null) {
logger.error('No such reply target.', { replyId: ps.replyId });
@ -384,11 +420,8 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
throw new ApiError(meta.errors.cannotReplyToInvisibleNote);
} else if (reply.visibility === 'specified' && ps.visibility !== 'specified') {
throw new ApiError(meta.errors.cannotReplyToSpecifiedVisibilityNoteWithExtendedVisibility);
} else if ( me.isBot ) {
const replayuser = await this.usersRepository.findOneBy({ id: reply.userId });
if (replayuser?.isBot) {
throw new ApiError(meta.errors.replyingToAnotherBot);
}
} else if (me.isBot && reply.user!.isBot) {
throw new ApiError(meta.errors.replyingToAnotherBot);
}
// Check blocking
@ -427,10 +460,23 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
}
}
let scheduledAt: Date | null = null;
if (ps.scheduledAt) {
const now = new Date();
scheduledAt = new Date(ps.scheduledAt);
scheduledAt.setMilliseconds(0);
if (scheduledAt < now) {
logger.error('Cannot schedule to the past.', { scheduledAt });
throw new ApiError(meta.errors.cannotScheduleToPast);
}
}
// 投稿を作成
try {
const note = await this.noteCreateService.create(me, {
createdAt: new Date(),
scheduledAt: ps.scheduledAt ? scheduledAt : null,
files: files,
poll: ps.poll ? {
choices: ps.poll.choices,
@ -454,10 +500,18 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
// 1分間、リクエストの処理結果を記録
await this.redisForTimelines.set(`note:idempotent:${me.id}:${hash}`, note.id, 'EX', 60);
logger.info('Successfully created a note.', { noteId: note.id });
if (ps.noCreatedNote) return;
if (!scheduledAt) {
logger.info('Successfully created a note.', { noteId: note.id });
} else {
this.notificationService.createNotification(me.id, "noteScheduled", {
draftId: note.id,
});
logger.info('Successfully scheduled a note.', { draftId: note.id });
}
if (ps.noCreatedNote || scheduledAt) return;
else return {
createdNote: await this.noteEntityService.pack(note, me),
createdNote: await this.noteEntityService.pack(note as MiNote, me),
};
} catch (err) {
// エラーが発生した場合、まだ処理中として記録されている場合はリクエストの処理結果を削除
@ -466,8 +520,12 @@ export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-
logger.error('Failed to create a note.', { error: err });
if (err instanceof IdentifiableError) {
if (err.id === '689ee33f-f97c-479a-ac49-1b9f8140af99') throw new ApiError(meta.errors.containsProhibitedWords);
if (err.id === '9f466dab-c856-48cd-9e65-ff90ff750580') throw new ApiError(meta.errors.containsTooManyMentions);
if (err.id === '689ee33f-f97c-479a-ac49-1b9f8140af99') throw new ApiError(meta.errors.containsProhibitedWords, { message: err.message });
if (err.id === '9f466dab-c856-48cd-9e65-ff90ff750580') throw new ApiError(meta.errors.containsTooManyMentions, { message: err.message });
if (err.id === '5ea8e4f5-9d64-4e6c-92b8-9e2b5a4756bc') throw new ApiError(meta.errors.cannotScheduleSameTime, { message: err.message });
if (err.id === '7fc78d25-d947-45c1-9547-02257b98cab3') throw new ApiError(meta.errors.tooManyScheduledNotes, { message: err.message });
if (err.id === '506006cf-3092-4ae1-8145-b025001c591f') throw new ApiError(meta.errors.cannotScheduleToFarFuture, { message: err.message });
if (err.id === '7cc42034-f7ab-4f7c-87b4-e00854479080') throw new ApiError(meta.errors.rolePermissionDenied, { message: err.message });
}
throw err;

View file

@ -0,0 +1,57 @@
import { Inject, Injectable } from '@nestjs/common';
import { Endpoint } from '@/server/api/endpoint-base.js';
import { DI } from '@/di-symbols.js';
import type { ScheduledNotesRepository } from '@/models/_.js';
import { QueueService } from '@/core/QueueService.js';
import { ApiError } from '@/server/api/error.js';
import ms from 'ms';
export const meta = {
tags: ['notes'],
requireCredential: true,
requireRolePolicy: 'canCreateContent',
prohibitMoved: true,
limit: {
duration: ms('1hour'),
max: 300,
},
kind: 'write:notes',
errors: {
noSuchDraft: {
message: 'No such draft',
code: 'NO_SUCH_DRAFT',
id: '91c2ad21-fb45-4f2a-ba4c-ea749b262947',
}
},
} as const;
export const paramDef = {
type: 'object',
properties: {
draftId: { type: 'string', format: 'misskey:id' },
},
required: ['draftId'],
} as const;
@Injectable()
export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-disable-line import/no-default-export
constructor(
@Inject(DI.scheduledNotesRepository)
private scheduledNotesRepository: ScheduledNotesRepository,
private queueService: QueueService,
) {
super(meta, paramDef, async (ps, me) => {
const draft = await this.scheduledNotesRepository.findOneBy({ id: ps.draftId, userId: me.id });
if (!draft) throw new ApiError(meta.errors.noSuchDraft);
await this.queueService.systemQueue.remove(`scheduledNote:${draft.id}`);
await this.scheduledNotesRepository.delete({ id: draft.id });
});
}
}

View file

@ -0,0 +1,49 @@
import { Inject, Injectable } from '@nestjs/common';
import { Endpoint } from '@/server/api/endpoint-base.js';
import { DI } from '@/di-symbols.js';
import type { ScheduledNotesRepository } from '@/models/_.js';
import { ScheduledNoteEntityService } from '@/core/entities/ScheduledNoteEntityService.js';
export const meta = {
tags: ['notes'],
requireCredential: true,
requireRolePolicy: 'canScheduleNote',
kind: 'write:notes',
res: {
type: 'array',
optional: false, nullable: false,
items: {
type: 'object',
optional: false, nullable: false,
ref: 'NoteDraft',
},
},
} as const;
export const paramDef = {
type: 'object',
properties: {
limit: { type: 'integer', minimum: 1, maximum: 100, default: 10 },
offset: { type: 'integer', default: 0 },
},
} as const;
@Injectable()
export default class extends Endpoint<typeof meta, typeof paramDef> { // eslint-disable-line import/no-default-export
constructor(
@Inject(DI.scheduledNotesRepository)
private scheduledNotesRepository: ScheduledNotesRepository,
private scheduledNoteEntityService: ScheduledNoteEntityService,
) {
super(meta, paramDef, async (ps, me) => {
const query = this.scheduledNotesRepository.createQueryBuilder('draft').where('draft.userId = :userId', { userId: me.id });
const drafts = await query.orderBy('draft.scheduledAt', 'ASC', 'NULLS FIRST').offset(ps.offset).limit(ps.limit).getMany();
return await this.scheduledNoteEntityService.packMany(drafts, me);
});
}
}

View file

@ -1,8 +1,10 @@
import { Schema } from '@/misc/json-schema.js';
import * as mep___accounts_lookup_v1_get from './mastodon/accounts/lookup/v1/get.js';
import * as mep___apps_v1_post from './mastodon/apps/v1/post.js';
const eps = [
['GET', 'v1/accounts/lookup', mep___accounts_lookup_v1_get],
['POST', 'v1/apps', mep___apps_v1_post],
];
export interface IMastodonEndpointMeta {

View file

@ -0,0 +1,80 @@
import { Inject, Injectable } from '@nestjs/common';
import { MastodonEndpoint } from '@/server/api/mastodon-endpoint-base.js';
import { MastodonApiError } from '@/server/api/error.js';
import { secureRndstr } from '@/misc/secure-rndstr.js';
import type { AppsRepository } from '@/models/_.js';
import { DI } from '@/di-symbols.js';
import { IdService } from '@/core/IdService.js';
import { mastodonToMisskeyScopes } from '@/misc/mastodon/mastodon-to-misskey-scopes.js';
export const meta = {
requireCredential: false,
} as const;
export const paramDef = {
type: 'object',
properties: {
client_name: { type: 'string', minLength: 1 },
redirect_uri: { type: 'string', minLength: 1 },
redirect_uris: {
anyOf: [
{ type: 'array', minItems: 1, items: { type: 'string', minLength: 1 } },
{ type: 'string', minLength: 1 },
],
},
scopes: { type: 'string', minLength: 1 },
website: { type: 'string' },
},
anyOf: [
{ required: ['redirect_uri'] },
{ required: ['redirect_uris'] },
],
required: ['client_name'],
} as const;
@Injectable()
export default class extends MastodonEndpoint<typeof meta, typeof paramDef> { // eslint-disable-line import/no-default-export
constructor(
@Inject(DI.appsRepository)
private appsRepository: AppsRepository,
private idService: IdService,
) {
super(meta, paramDef, async (ps, me) => {
const redirectUrlsRawValue = ps.redirect_uris ?? ps.redirect_uri ?? [];
const redirectUris = typeof redirectUrlsRawValue === 'string' ? redirectUrlsRawValue.split('\n') : redirectUrlsRawValue;
const secret = secureRndstr(32);
const mastodonScopes = (ps.scopes ?? 'read').split(' ');
const scopes = mastodonScopes.flatMap(scope => {
const misskeyScopes = mastodonToMisskeyScopes.get(scope);
if (!misskeyScopes) {
throw new MastodonApiError('Scopes doesn\'t match configured on the server.', 400);
}
return misskeyScopes;
});
const clientId = this.idService.gen();
await this.appsRepository.insert({
id: clientId,
userId: me ? me.id : null,
name: ps.client_name,
description: ps.website ?? '',
permission: scopes,
callbackUrl: null,
secret: secret,
website: ps.website,
mastodonScopes: mastodonScopes,
redirectUris: redirectUris,
});
return {
id: clientId,
name: ps.client_name,
website: ps.website,
scopes: mastodonScopes,
redirect_uri: redirectUris.join('\n'),
redirect_uris: redirectUris,
client_id: `mastodon:${clientId}`,
client_secret: secret,
};
});
}
}

View file

@ -51,6 +51,10 @@ class AntennaChannel extends Channel {
if (this.isNoteMutedOrBlocked(note)) return;
if (this.user && (note.visibleUserIds?.includes(this.user.id) ?? note.mentions?.includes(this.user.id))) {
this.connection.cacheNote(note);
}
if (this.minimize && ['public', 'home'].includes(note.visibility)) {
this.send('note', {
id: note.id, myReaction: note.myReaction,
@ -59,7 +63,6 @@ class AntennaChannel extends Channel {
renote: note.renote?.myReaction ? { myReaction: note.renote.myReaction } : undefined,
});
} else {
this.connection.cacheNote(note);
this.send('note', note);
}
} else {

View file

@ -57,6 +57,10 @@ class ChannelChannel extends Channel {
}
}
if (this.user && (note.visibleUserIds?.includes(this.user.id) ?? note.mentions?.includes(this.user.id))) {
this.connection.cacheNote(note);
}
if (this.minimize && ['public', 'home'].includes(note.visibility)) {
this.send('note', {
id: note.id, myReaction: note.myReaction,
@ -65,7 +69,6 @@ class ChannelChannel extends Channel {
renote: note.renote?.myReaction ? { myReaction: note.renote.myReaction } : undefined,
});
} else {
this.connection.cacheNote(note);
this.send('note', note);
}
}

View file

@ -87,6 +87,10 @@ class GlobalTimelineChannel extends Channel {
}
}
if (this.user && (note.visibleUserIds?.includes(this.user.id) ?? note.mentions?.includes(this.user.id))) {
this.connection.cacheNote(note);
}
if (this.minimize && ['public', 'home'].includes(note.visibility)) {
this.send('note', {
id: note.id, myReaction: note.myReaction,
@ -95,7 +99,6 @@ class GlobalTimelineChannel extends Channel {
renote: note.renote?.myReaction ? { myReaction: note.renote.myReaction } : undefined,
});
} else {
this.connection.cacheNote(note);
this.send('note', note);
}
}

View file

@ -60,7 +60,9 @@ class HashtagChannel extends Channel {
}
}
this.connection.cacheNote(note);
if (this.user && (note.visibleUserIds?.includes(this.user.id) ?? note.mentions?.includes(this.user.id))) {
this.connection.cacheNote(note);
}
this.send('note', note);
}

View file

@ -91,6 +91,10 @@ class HomeTimelineChannel extends Channel {
}
}
if (this.user && (note.visibleUserIds?.includes(this.user.id) ?? note.mentions?.includes(this.user.id))) {
this.connection.cacheNote(note);
}
if (this.minimize && ['public', 'home'].includes(note.visibility)) {
this.send('note', {
id: note.id, myReaction: note.myReaction,
@ -99,7 +103,6 @@ class HomeTimelineChannel extends Channel {
renote: note.renote?.myReaction ? { myReaction: note.renote.myReaction } : undefined,
});
} else {
this.connection.cacheNote(note);
this.send('note', note);
}
}

View file

@ -105,6 +105,10 @@ class HybridTimelineChannel extends Channel {
}
}
if (this.user && (note.visibleUserIds?.includes(this.user.id) ?? note.mentions?.includes(this.user.id))) {
this.connection.cacheNote(note);
}
if (this.minimize && ['public', 'home'].includes(note.visibility)) {
this.send('note', {
id: note.id, myReaction: note.myReaction,
@ -113,7 +117,6 @@ class HybridTimelineChannel extends Channel {
renote: note.renote?.myReaction ? { myReaction: note.renote.myReaction } : undefined,
});
} else {
this.connection.cacheNote(note);
this.send('note', note);
}
}

View file

@ -90,6 +90,10 @@ class LocalTimelineChannel extends Channel {
}
}
if (this.user && (note.visibleUserIds?.includes(this.user.id) ?? note.mentions?.includes(this.user.id))) {
this.connection.cacheNote(note);
}
if (this.minimize && ['public', 'home'].includes(note.visibility)) {
this.send('note', {
id: note.id, myReaction: note.myReaction,
@ -98,7 +102,6 @@ class LocalTimelineChannel extends Channel {
renote: note.renote?.myReaction ? { myReaction: note.renote.myReaction } : undefined,
});
} else {
this.connection.cacheNote(note);
this.send('note', note);
}
}

View file

@ -38,7 +38,11 @@ class MainChannel extends Channel {
const note = await this.noteEntityService.pack(data.body.note.id, this.user, {
detail: true,
});
this.connection.cacheNote(note);
if (this.user && (note.visibleUserIds?.includes(this.user.id) ?? note.mentions?.includes(this.user.id))) {
this.connection.cacheNote(note);
}
data.body.note = note;
}
break;
@ -51,7 +55,11 @@ class MainChannel extends Channel {
const note = await this.noteEntityService.pack(data.body.id, this.user, {
detail: true,
});
this.connection.cacheNote(note);
if (this.user && (note.visibleUserIds?.includes(this.user.id) ?? note.mentions?.includes(this.user.id))) {
this.connection.cacheNote(note);
}
data.body = note;
}
break;

View file

@ -73,6 +73,10 @@ class RoleTimelineChannel extends Channel {
}
}
if (this.user && (note.visibleUserIds?.includes(this.user.id) ?? note.mentions?.includes(this.user.id))) {
this.connection.cacheNote(note);
}
if (this.minimize && ['public', 'home'].includes(note.visibility)) {
this.send('note', {
id: note.id, myReaction: note.myReaction,
@ -81,7 +85,6 @@ class RoleTimelineChannel extends Channel {
renote: note.renote?.myReaction ? { myReaction: note.renote.myReaction } : undefined,
});
} else {
this.connection.cacheNote(note);
this.send('note', note);
}
} else {

View file

@ -130,6 +130,10 @@ class UserListChannel extends Channel {
}
}
if (this.user && (note.visibleUserIds?.includes(this.user.id) ?? note.mentions?.includes(this.user.id))) {
this.connection.cacheNote(note);
}
if (this.minimize && ['public', 'home'].includes(note.visibility)) {
this.send('note', {
id: note.id, myReaction: note.myReaction,
@ -138,7 +142,6 @@ class UserListChannel extends Channel {
renote: note.renote?.myReaction ? { myReaction: note.renote.myReaction } : undefined,
});
} else {
this.connection.cacheNote(note);
this.send('note', note);
}
}

View file

@ -34,6 +34,7 @@ import { DI } from '@/di-symbols.js';
import { bindThis } from '@/decorators.js';
import type {
AccessTokensRepository,
AppsRepository,
IndieAuthClientsRepository,
UserProfilesRepository,
UsersRepository,
@ -45,9 +46,15 @@ import { LoggerService } from '@/core/LoggerService.js';
import Logger from '@/logger.js';
import { StatusError } from '@/misc/status-error.js';
import { normalizeEmailAddress } from '@/misc/normalize-email-address.js';
import { mastodonToMisskeyScopes } from '@/misc/mastodon/mastodon-to-misskey-scopes.js';
import type { ServerResponse } from 'node:http';
import type { FastifyInstance } from 'fastify';
function extractMastodonAppId(clientId: string): string | null {
const MASTODON_CLIENT_ID_PREFIX = 'mastodon:';
return clientId.startsWith(MASTODON_CLIENT_ID_PREFIX) ? clientId.substring(MASTODON_CLIENT_ID_PREFIX.length) : null;
}
// TODO: Consider migrating to @node-oauth/oauth2-server once
// https://github.com/node-oauth/node-oauth2-server/issues/180 is figured out.
// Upstream the various validations and RFC9207 implementation in that case.
@ -258,6 +265,8 @@ export class OAuth2ProviderService {
private usersRepository: UsersRepository,
@Inject(DI.userProfilesRepository)
private userProfilesRepository: UserProfilesRepository,
@Inject(DI.appsRepository)
private appsRepository: AppsRepository,
private idService: IdService,
private cacheService: CacheService,
@ -328,13 +337,25 @@ export class OAuth2ProviderService {
if (body.client_id !== granted.clientId) return;
if (redirectUri !== granted.redirectUri) return;
const mastodonAppId = extractMastodonAppId(granted.clientId);
// https://datatracker.ietf.org/doc/html/rfc7636.html#section-4.6
if (!body.code_verifier) return;
if (!(await verifyChallenge(body.code_verifier as string, granted.codeChallenge))) return;
// For Mastodon API, code verifier isn't necessary (but if code challenge was provided, then it should be verified)
if (!mastodonAppId || granted.codeChallenge || body.code_verifier) {
if (!body.code_verifier) return;
if (!(await verifyChallenge(body.code_verifier as string, granted.codeChallenge))) return;
}
const accessToken = secureRndstr(128);
const now = new Date();
let scopes = granted.scopes;
let name = granted.clientId;
if (mastodonAppId) {
scopes = [...new Set(granted.scopes.flatMap((scope: string) => mastodonToMisskeyScopes.get(scope)))];
name = (await this.appsRepository.findOneBy({ id: mastodonAppId }))?.name ?? name;
}
// NOTE: we don't have a setup for automatic token expiration
await accessTokensRepository.insert({
id: idService.gen(now.getTime()),
@ -342,8 +363,9 @@ export class OAuth2ProviderService {
userId: granted.userId,
token: accessToken,
hash: accessToken,
name: granted.clientId,
permission: granted.scopes,
name: name,
permission: scopes,
appId: mastodonAppId,
});
grantedState = await this.redisClient.get(`oauth2:authorization:${code}:state`);
@ -354,7 +376,7 @@ export class OAuth2ProviderService {
}
granted.grantedToken = accessToken;
this.#logger.info(`Generated access token for ${granted.clientId} for user ${granted.userId}, with scope: [${granted.scopes}]`);
this.#logger.info(`Generated access token for ${granted.clientId} for user ${granted.userId}, with scope: [${scopes}]`);
await this.redisClient.set(`oauth2:authorization:${code}`, JSON.stringify(granted), 'EX', 60 * 5);
return [accessToken, undefined, { scope: granted.scopes.join(' ') }];
@ -418,50 +440,75 @@ export class OAuth2ProviderService {
this.#logger.info(`Validating authorization parameters, with client_id: ${clientID}, redirect_uri: ${redirectURI}, scope: ${scope}`);
const clientUrl = validateClientId(clientID);
let clientInfo: ClientInformation;
const mastodonAppId = extractMastodonAppId(clientID);
if (mastodonAppId) {
const app = await this.appsRepository.findOneBy({ id: mastodonAppId });
if (!app) {
throw new AuthorizationError('unrecognized client id', 'invalid_request');
}
clientInfo = {
id: clientID,
name: app.name,
redirectUris: app.redirectUris,
};
if (codeChallengeMethod && codeChallengeMethod !== 'S256') {
throw new AuthorizationError('`code_challenge_method` parameter must be set as S256', 'invalid_request');
}
try {
const scopes = [...new Set(scope)].filter(s => mastodonToMisskeyScopes.has(s));
if (!scopes.length) {
throw new AuthorizationError('`scope` parameter has no known scope', 'invalid_scope');
}
areq.scope = scopes;
} catch (err) {
return [err as Error, clientInfo, redirectURI];
}
} else {
const clientUrl = validateClientId(clientID);
// https://indieauth.spec.indieweb.org/#client-information-discovery
// "the server may want to resolve the domain name first and avoid fetching the document
// if the IP address is within the loopback range defined by [RFC5735]
// or any other implementation-specific internal IP address."
if (process.env.NODE_ENV !== 'test' || process.env.MISSKEY_TEST_CHECK_IP_RANGE === '1') {
const lookup = await dns.lookup(clientUrl.hostname);
if (ipaddr.parse(lookup.address).range() !== 'unicast') {
throw new AuthorizationError('client_id resolves to disallowed IP range.', 'invalid_request');
// https://indieauth.spec.indieweb.org/#client-information-discovery
// "the server may want to resolve the domain name first and avoid fetching the document
// if the IP address is within the loopback range defined by [RFC5735]
// or any other implementation-specific internal IP address."
if (process.env.NODE_ENV !== 'test' || process.env.MISSKEY_TEST_CHECK_IP_RANGE === '1') {
const lookup = await dns.lookup(clientUrl.hostname);
if (ipaddr.parse(lookup.address).range() !== 'unicast') {
throw new AuthorizationError('client_id resolves to disallowed IP range.', 'invalid_request');
}
}
// Find client information from the database.
const registeredClientInfo = await this.indieAuthClientsRepository.findOneBy({ id: clientUrl.href }) as ClientInformation | null;
// Find client information from the remote.
clientInfo = registeredClientInfo ?? await discoverClientInformation(this.#logger, this.httpRequestService, clientUrl.href);
try {
const scopes = [...new Set(scope)].filter(s => (<readonly string[]>kinds).includes(s));
if (!scopes.length) {
throw new AuthorizationError('`scope` parameter has no known scope', 'invalid_scope');
}
areq.scope = scopes;
// Require PKCE parameters. This requirement is skipped for Mastodon clients, as Mastodon API doesn't require it.
// Recommended by https://indieauth.spec.indieweb.org/#authorization-request, but also prevents downgrade attack:
// https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics#name-pkce-downgrade-attack
if (typeof codeChallenge !== 'string') {
throw new AuthorizationError('`code_challenge` parameter is required', 'invalid_request');
}
if (codeChallengeMethod !== 'S256') {
throw new AuthorizationError('`code_challenge_method` parameter must be set as S256', 'invalid_request');
}
} catch (err) {
return [err as Error, clientInfo, redirectURI];
}
}
// Find client information from the database.
const registeredClientInfo = await this.indieAuthClientsRepository.findOneBy({ id: clientUrl.href }) as ClientInformation | null;
// Find client information from the remote.
const clientInfo = registeredClientInfo ?? await discoverClientInformation(this.#logger, this.httpRequestService, clientUrl.href);
// Require the redirect URI to be included in an explicit list, per
// https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics#section-4.1.3
if (!clientInfo.redirectUris.includes(redirectURI)) {
throw new AuthorizationError('Invalid redirect_uri', 'invalid_request');
}
try {
const scopes = [...new Set(scope)].filter(s => (<readonly string[]>kinds).includes(s));
if (!scopes.length) {
throw new AuthorizationError('`scope` parameter has no known scope', 'invalid_scope');
}
areq.scope = scopes;
// Require PKCE parameters.
// Recommended by https://indieauth.spec.indieweb.org/#authorization-request, but also prevents downgrade attack:
// https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics#name-pkce-downgrade-attack
if (typeof codeChallenge !== 'string') {
throw new AuthorizationError('`code_challenge` parameter is required', 'invalid_request');
}
if (codeChallengeMethod !== 'S256') {
throw new AuthorizationError('`code_challenge_method` parameter must be set as S256', 'invalid_request');
}
} catch (err) {
return [err as Error, clientInfo, redirectURI];
}
return [null, clientInfo, redirectURI];
})().then(args => done(...args), err => done(err));
}) as ValidateFunctionArity2));

View file

@ -3,6 +3,13 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
import type { MiDriveFile } from '@/models/DriveFile.js';
import type { IPoll } from '@/models/Poll.js';
import type { MiChannel } from '@/models/Channel.js';
import type { MiApp } from '@/models/App.js';
import type { MiUser } from '@/models/User.js';
import type { MiNote } from '@/models/Note.js';
/**
* note - 稿
* follow -
@ -16,6 +23,9 @@
* followRequestAccepted -
* roleAssigned -
* achievementEarned -
* noteScheduled - 稿
* scheduledNotePosted - 稿稿
* scheduledNoteError - 稿
* app -
* test -
*/
@ -32,6 +42,9 @@ export const notificationTypes = [
'followRequestAccepted',
'roleAssigned',
'achievementEarned',
'noteScheduled',
'scheduledNotePosted',
'scheduledNoteError',
'app',
'test',
] as const;
@ -350,6 +363,36 @@ export type ModerationLogPayloads = {
}
};
export type MinimumUser = {
id: MiUser['id'];
host: MiUser['host'];
username: MiUser['username'];
uri: MiUser['uri'];
};
export type NoteCreateOption = {
createdAt?: Date | null;
scheduledAt?: Date | null;
name?: string | null;
text?: string | null;
reply?: MiNote | null;
renote?: MiNote | null;
files?: MiDriveFile[] | null;
poll?: IPoll | null;
localOnly?: boolean | null;
reactionAcceptance?: MiNote['reactionAcceptance'];
cw?: string | null;
visibility?: string;
visibleUsers?: MinimumUser[] | null;
channel?: MiChannel | null;
apMentions?: MinimumUser[] | null;
apHashtags?: string[] | null;
apEmojis?: string[] | null;
uri?: string | null;
url?: string | null;
app?: MiApp | null;
};
export type Serialized<T> = {
[K in keyof T]:
T[K] extends Date

View file

@ -40,6 +40,7 @@ describe('ユーザー', () => {
avatarDecorations: user.avatarDecorations,
isBot: user.isBot,
isCat: user.isCat,
speakAsCat: user.speakAsCat,
instance: user.instance,
emojis: user.emojis,
onlineStatus: user.onlineStatus,
@ -311,6 +312,7 @@ describe('ユーザー', () => {
assert.deepStrictEqual(response.avatarDecorations, []);
assert.strictEqual(response.isBot, false);
assert.strictEqual(response.isCat, false);
assert.strictEqual(response.speakAsCat, false);
assert.strictEqual(response.instance, undefined);
assert.deepStrictEqual(response.emojis, {});
assert.strictEqual(response.onlineStatus, 'unknown');
@ -446,6 +448,8 @@ describe('ユーザー', () => {
{ parameters: () => ({ isBot: false }) },
{ parameters: () => ({ isCat: true }) },
{ parameters: () => ({ isCat: false }) },
{ parameters: () => ({ speakAsCat: true }) },
{ parameters: () => ({ speakAsCat: false }) },
{ parameters: () => ({ injectFeaturedNote: true }) },
{ parameters: () => ({ injectFeaturedNote: false }) },
{ parameters: () => ({ receiveAnnouncementEmail: true }) },

View file

@ -9,6 +9,7 @@ import * as assert from 'assert';
import { jest } from '@jest/globals';
import * as lolex from '@sinonjs/fake-timers';
import { DataSource } from 'typeorm';
import * as Redis from 'ioredis';
import TestChart from '@/core/chart/charts/test.js';
import TestGroupedChart from '@/core/chart/charts/test-grouped.js';
import TestUniqueChart from '@/core/chart/charts/test-unique.js';
@ -18,16 +19,16 @@ import { entity as TestGroupedChartEntity } from '@/core/chart/charts/entities/t
import { entity as TestUniqueChartEntity } from '@/core/chart/charts/entities/test-unique.js';
import { entity as TestIntersectionChartEntity } from '@/core/chart/charts/entities/test-intersection.js';
import { loadConfig } from '@/config.js';
import type { AppLockService } from '@/core/AppLockService.js';
import { coreLogger } from '@/logger.js';
describe('Chart', () => {
const config = loadConfig();
const appLockService = {
getChartInsertLock: () => () => Promise.resolve(() => {}),
} as unknown as jest.Mocked<AppLockService>;
let db: DataSource | undefined;
let redisForTimelines = {
set: () => Promise.resolve('OK'),
get: () => Promise.resolve(null),
} as unknown as jest.Mocked<Redis.Redis>;
let testChart: TestChart;
let testGroupedChart: TestGroupedChart;
@ -64,10 +65,10 @@ describe('Chart', () => {
await db.initialize();
const logger = coreLogger.createSubLogger('chart'); // TODO: モックにする
testChart = new TestChart(db, appLockService, logger);
testGroupedChart = new TestGroupedChart(db, appLockService, logger);
testUniqueChart = new TestUniqueChart(db, appLockService, logger);
testIntersectionChart = new TestIntersectionChart(db, appLockService, logger);
testChart = new TestChart(db, redisForTimelines, logger);
testGroupedChart = new TestGroupedChart(db, redisForTimelines, logger);
testUniqueChart = new TestUniqueChart(db, redisForTimelines, logger);
testIntersectionChart = new TestIntersectionChart(db, redisForTimelines, logger);
clock = lolex.install({
now: new Date(Date.UTC(2000, 0, 1, 0, 0, 0)),

View file

@ -100,6 +100,7 @@ export function userDetailed(id = 'someuserid', username = 'miskist', host = 'mi
isBlocking: false,
isBot: false,
isCat: false,
speakAsCat: false,
isFollowed: false,
isFollowing: false,
isLocked: false,

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