refactor (backend): port publishAdminStream to backend-rs

This commit is contained in:
naskya 2024-04-26 05:44:37 +09:00
parent 23e57737a6
commit 79ab7bf787
No known key found for this signature in database
GPG key ID: 712D413B3A9FED5C
6 changed files with 51 additions and 23 deletions

View file

@ -1156,6 +1156,13 @@ export enum ChatEvent {
Typing = 'typing' Typing = 'typing'
} }
export function publishToChatStream(senderUserId: string, receiverUserId: string, kind: ChatEvent, object: any): void export function publishToChatStream(senderUserId: string, receiverUserId: string, kind: ChatEvent, object: any): void
export interface AbuseUserReportLike {
id: string
targetUserId: string
reporterId: string
comment: string
}
export function publishToModerationStream(moderatorId: string, report: AbuseUserReportLike): void
export function getTimestamp(id: string): number export function getTimestamp(id: string): number
/** /**
* The generated ID results in the form of `[8 chars timestamp] + [cuid2]`. * The generated ID results in the form of `[8 chars timestamp] + [cuid2]`.

View file

@ -310,7 +310,7 @@ if (!nativeBinding) {
throw new Error(`Failed to load native binding`) throw new Error(`Failed to load native binding`)
} }
const { SECOND, MINUTE, HOUR, DAY, USER_ONLINE_THRESHOLD, USER_ACTIVE_THRESHOLD, FILE_TYPE_BROWSERSAFE, loadEnv, loadConfig, stringToAcct, acctToString, addNoteToAntenna, isBlockedServer, isSilencedServer, isAllowedServer, checkWordMute, getFullApAccount, isSelfHost, isSameOrigin, extractHost, toPuny, isUnicodeEmoji, sqlLikeEscape, safeForSql, formatMilliseconds, getImageSizeFromUrl, getNoteSummary, toMastodonId, fromMastodonId, fetchMeta, metaToPugArgs, nyaify, hashPassword, verifyPassword, isOldPasswordAlgorithm, decodeReaction, countReactions, toDbReaction, removeOldAttestationChallenges, AntennaSrcEnum, DriveFileUsageHintEnum, MutedNoteReasonEnum, NoteVisibilityEnum, NotificationTypeEnum, PageVisibilityEnum, PollNotevisibilityEnum, RelayStatusEnum, UserEmojimodpermEnum, UserProfileFfvisibilityEnum, UserProfileMutingnotificationtypesEnum, initializeRustLogger, watchNote, unwatchNote, ChatEvent, publishToChatStream, getTimestamp, genId, genIdAt, secureRndstr } = nativeBinding const { SECOND, MINUTE, HOUR, DAY, USER_ONLINE_THRESHOLD, USER_ACTIVE_THRESHOLD, FILE_TYPE_BROWSERSAFE, loadEnv, loadConfig, stringToAcct, acctToString, addNoteToAntenna, isBlockedServer, isSilencedServer, isAllowedServer, checkWordMute, getFullApAccount, isSelfHost, isSameOrigin, extractHost, toPuny, isUnicodeEmoji, sqlLikeEscape, safeForSql, formatMilliseconds, getImageSizeFromUrl, getNoteSummary, toMastodonId, fromMastodonId, fetchMeta, metaToPugArgs, nyaify, hashPassword, verifyPassword, isOldPasswordAlgorithm, decodeReaction, countReactions, toDbReaction, removeOldAttestationChallenges, AntennaSrcEnum, DriveFileUsageHintEnum, MutedNoteReasonEnum, NoteVisibilityEnum, NotificationTypeEnum, PageVisibilityEnum, PollNotevisibilityEnum, RelayStatusEnum, UserEmojimodpermEnum, UserProfileFfvisibilityEnum, UserProfileMutingnotificationtypesEnum, initializeRustLogger, watchNote, unwatchNote, ChatEvent, publishToChatStream, publishToModerationStream, getTimestamp, genId, genIdAt, secureRndstr } = nativeBinding
module.exports.SECOND = SECOND module.exports.SECOND = SECOND
module.exports.MINUTE = MINUTE module.exports.MINUTE = MINUTE
@ -367,6 +367,7 @@ module.exports.watchNote = watchNote
module.exports.unwatchNote = unwatchNote module.exports.unwatchNote = unwatchNote
module.exports.ChatEvent = ChatEvent module.exports.ChatEvent = ChatEvent
module.exports.publishToChatStream = publishToChatStream module.exports.publishToChatStream = publishToChatStream
module.exports.publishToModerationStream = publishToModerationStream
module.exports.getTimestamp = getTimestamp module.exports.getTimestamp = getTimestamp
module.exports.genId = genId module.exports.genId = genId
module.exports.genIdAt = genIdAt module.exports.genIdAt = genIdAt

View file

@ -1,5 +1,6 @@
pub mod antenna; pub mod antenna;
pub mod chat; pub mod chat;
pub mod moderation;
use crate::config::CONFIG; use crate::config::CONFIG;
use crate::database::redis_conn; use crate::database::redis_conn;
@ -11,8 +12,8 @@ pub enum Stream {
Internal, Internal,
#[strum(serialize = "broadcast")] #[strum(serialize = "broadcast")]
Broadcast, Broadcast,
#[strum(to_string = "adminStream:{user_id}")] #[strum(to_string = "adminStream:{moderator_id}")]
Admin { user_id: String }, Moderation { moderator_id: String },
#[strum(to_string = "user:{user_id}")] #[strum(to_string = "user:{user_id}")]
User { user_id: String }, User { user_id: String },
#[strum(to_string = "channelStream:{channel_id}")] #[strum(to_string = "channelStream:{channel_id}")]
@ -86,8 +87,8 @@ mod unit_test {
assert_eq!(Stream::Internal.to_string(), "internal"); assert_eq!(Stream::Internal.to_string(), "internal");
assert_eq!(Stream::Broadcast.to_string(), "broadcast"); assert_eq!(Stream::Broadcast.to_string(), "broadcast");
assert_eq!( assert_eq!(
Stream::Admin { Stream::Moderation {
user_id: "9tb42br63g5apjcq".to_string() moderator_id: "9tb42br63g5apjcq".to_string()
} }
.to_string(), .to_string(),
"adminStream:9tb42br63g5apjcq" "adminStream:9tb42br63g5apjcq"

View file

@ -0,0 +1,21 @@
use crate::service::stream::{publish_to_stream, Error, Stream};
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[crate::export(object)]
pub struct AbuseUserReportLike {
pub id: String,
pub target_user_id: String,
pub reporter_id: String,
pub comment: String,
}
#[crate::export(js_name = "publishToModerationStream")]
pub fn publish(moderator_id: String, report: &AbuseUserReportLike) -> Result<(), Error> {
publish_to_stream(
&Stream::Moderation { moderator_id },
Some("newAbuseUserReport".to_string()),
Some(serde_json::to_string(report)?),
)
}

View file

@ -1,10 +1,8 @@
import * as mfm from "mfm-js"; import * as mfm from "mfm-js";
import sanitizeHtml from "sanitize-html"; import sanitizeHtml from "sanitize-html";
import { publishAdminStream } from "@/services/stream.js";
import { AbuseUserReports, UserProfiles, Users } from "@/models/index.js"; import { AbuseUserReports, UserProfiles, Users } from "@/models/index.js";
import { genId } from "backend-rs"; import { genId, publishToModerationStream } from "backend-rs";
import { sendEmail } from "@/services/send-email.js"; import { sendEmail } from "@/services/send-email.js";
import { fetchMeta } from "backend-rs";
import { getUser } from "@/server/api/common/getters.js"; import { getUser } from "@/server/api/common/getters.js";
import { ApiError } from "@/server/api/error.js"; import { ApiError } from "@/server/api/error.js";
import define from "@/server/api/define.js"; import define from "@/server/api/define.js";
@ -86,9 +84,8 @@ export default define(meta, paramDef, async (ps, me) => {
], ],
}); });
const meta = await fetchMeta(true);
for (const moderator of moderators) { for (const moderator of moderators) {
publishAdminStream(moderator.id, "newAbuseUserReport", { publishToModerationStream(moderator.id, {
id: report.id, id: report.id,
targetUserId: report.targetUserId, targetUserId: report.targetUserId,
reporterId: report.reporterId, reporterId: report.reporterId,

View file

@ -8,7 +8,7 @@ import { config } from "@/config.js";
import type { Channel } from "@/models/entities/channel.js"; import type { Channel } from "@/models/entities/channel.js";
import type { import type {
StreamChannels, StreamChannels,
AdminStreamTypes, // AdminStreamTypes,
// AntennaStreamTypes, // AntennaStreamTypes,
BroadcastTypes, BroadcastTypes,
ChannelStreamTypes, ChannelStreamTypes,
@ -193,17 +193,18 @@ class Publisher {
this.publish("notesStream", null, note); this.publish("notesStream", null, note);
}; };
public publishAdminStream = <K extends keyof AdminStreamTypes>( /* ported to backend-rs */
userId: User["id"], // public publishAdminStream = <K extends keyof AdminStreamTypes>(
type: K, // userId: User["id"],
value?: AdminStreamTypes[K], // type: K,
): void => { // value?: AdminStreamTypes[K],
this.publish( // ): void => {
`adminStream:${userId}`, // this.publish(
type, // `adminStream:${userId}`,
typeof value === "undefined" ? null : value, // type,
); // typeof value === "undefined" ? null : value,
}; // );
// };
} }
const publisher = new Publisher(); const publisher = new Publisher();
@ -225,4 +226,4 @@ export const publishGroupMessagingStream =
publisher.publishGroupMessagingStream; publisher.publishGroupMessagingStream;
export const publishMessagingIndexStream = export const publishMessagingIndexStream =
publisher.publishMessagingIndexStream; publisher.publishMessagingIndexStream;
export const publishAdminStream = publisher.publishAdminStream; // export const publishAdminStream = publisher.publishAdminStream;