Files
discord-decomp/modules/rpc/RPCHelpers.tsx
T
2026-11-01 12:12:55 +02:00

465 lines
15 KiB
TypeScript

// Metro module 10631 (f10632).
import ApplicationStore from "../applications/ApplicationStore";
import ApplicationRecord from "../../records/ApplicationRecord";
import { GUILD_VOCAL_CHANNEL_TYPES } from "../../records/ChannelRecord";
import UserRecord from "../../records/UserRecord";
import ChannelStore from "../../stores/ChannelStore";
import GuildStore from "../../stores/GuildStore";
import MediaEngineStore from "../../stores/MediaEngineStore";
import MessageStore from "../../stores/MessageStore";
import PresenceStore from "../../stores/PresenceStore";
import UserStore from "../../stores/UserStore";
import VoiceStateStore from "../../stores/VoiceStateStore";
import { RPC_LOCAL_SCOPE, TransportTypes } from "./Constants";
import { ActivityActionTypes, ChannelTypes, Endpoints, MAX_MESSAGES_PER_CHANNEL, RPCCloseCodes, RPCErrors, RTCConnectionStates } from "../../Constants";
import URLUtils from "../../utils/URLUtils";
import RegexUtils from "../../utils/RegexUtils";
import Durations from "../../utils/Durations";
import Module12 from "../../_bundle/Module12";
import MessageActionCreators from "../../actions/MessageActionCreators";
import MarkupUtils from "../markup/MarkupUtils";
import { getUserAuthor } from "../messages/useMessageAuthor";
import transformUser from "./helpers/transformUser";
import NicknameUtils from "../../utils/NicknameUtils";
import Url from "../../_bundle/Url_1469";
import { OAuth2Scopes } from "../../_bundle/Module8174";
import { HTTP } from "../../_bundle/sendRequest";
import RPCError from "./RPCError";
import getURLForApplication from "../activities/getURLForApplication";
import LeakyBucket from "../../_bundle/LeakyBucket";
function $mk107395() {
return (a0, a1) => a0.index - a1.index;
}
function $mk107396() {
return (a0) => ({
id: a0.id,
name: a0.name
});
}
let c7133_24, c7133_25, c7133_26, validateOrigin, transformInternalTextMessage, fetchApplicationRPC;
const recurseReplaceContentTree = function recurseReplaceContentTree(a0) {
if (a0.type === "customEmoji") {
a0.type = "emoji";
}
if (a0.type === "emoji" && a0.src) {
const src = a0.src;
a0.src = /^http/.test(src) ? src : `${location.protocol}//${location.host}${src.charAt(0) === "/" ? "" : "/"}${src}`;
}
if (Array.isArray(a0.content)) {
a0.content = a0.content.map(recurseReplaceContentTree);
}
return a0;
};
validateOrigin = function validateOrigin(a0, r4 = []) {
return r4.indexOf(a0) > -1;
};
transformInternalTextMessage = function transformInternalTextMessage(message) {
const r21 = MarkupUtils.parseToAST(message.content, true, {
channelId: message.channel_id
}).map(recurseReplaceContentTree);
const channel = ChannelStore.getChannel(message.channel_id);
const r28 = message.author != null ? new UserRecord(message.author) : void 0;
const r33 = message.author != null ? getUserAuthor(r28, channel) : void 0;
return {
id: message.id,
blocked: message.blocked,
bot: message.bot,
content: message.content,
content_parsed: r21.length ? r21 : void 0,
nick: r33?.nick,
author_color: r33?.colorString,
edited_timestamp: message.edited_timestamp || message.editedTimestamp,
timestamp: message.timestamp,
tts: message.tts,
mentions: message.mentions,
mention_everyone: message.mention_everyone || message.mentionEveryone,
mention_roles: message.mention_roles || message.mentionRoles,
embeds: message.embeds,
attachments: message.attachments,
author: r28 != null ? transformUser(r28) : void 0,
pinned: message.pinned,
type: message.type
};
};
fetchApplicationRPC = function fetchApplicationRPC(a0) {
return HTTP.get({
url: Endpoints.APPLICATION_RPC(a0),
oldFormErrors: true,
retries: 3,
rejectWithError: true
}).then((result) => result.body, () => {
throw new RPCError({
closeCode: RPCCloseCodes.INVALID_CLIENTID
}, "Invalid Client ID");
});
};
let r76 = URLUtils.toURLSafe(window.GLOBAL_ENV.API_ENDPOINT)?.host;
if (r76 == null) {
r76 = "localhost";
}
let r80 = r76.split(":")[0];
const r83 = r80.includes(".");
let r18 = r80;
if (r83) {
const r85 = r80.split(".");
if (!/^\d+$/.test(r85[r85.length - 1])) {
r80 = r85.slice(-2).join(".");
}
r18 = r80;
}
export function getRemoteIconURL(a0) {
return /^http/.test(a0) ? a0 : `${location.protocol}//${location.host}${a0.charAt(0) === "/" ? "" : "/"}${a0}`;
}
export function transformVoiceState(a0, a1, { mute, deaf, selfMute, selfDeaf, suppress, userId }) {
const user = UserStore.getUser(userId);
if (user == null) {
throw new Error(`Invalid user id: ${userId}`);
}
return {
nick: NicknameUtils.getName(a0, a1, user),
mute: MediaEngineStore.isLocalMute(user.id),
volume: MediaEngineStore.getLocalVolume(user.id),
pan: MediaEngineStore.getLocalPan(user.id),
voice_state: {
mute,
deaf,
self_mute: selfMute,
self_deaf: selfDeaf,
suppress
},
user: transformUser(user)
};
}
c7133_24 = new RegExp(`^${RegexUtils.escape("https://")}(?:[a-z]+\\.)?(${RegexUtils.escape(r18)}|discordapp.com|discord.com)\$`);
c7133_25 = 1 * Durations.Millis.MINUTE;
c7133_26 = {};
export const VALIDATE_SOCKET_CALLS_PER_PERIOD_LOW = 2;
export const VALIDATE_SOCKET_CALLS_PER_PERIOD_HIGH = 60;
export { c7133_25 as VALIDATE_SOCKET_PERIOD_MS };
export { c7133_26 as VALIDATE_SOCKET_THROTTLERS };
export function containsSameValues(a0, a1) {
return Module12.isEqual(a0, Module12.pick(a1, Object.keys(a0)));
}
export { validateOrigin };
export function transformChannel(a0, c18160_1) {
const r11 = [];
const guildId = a0.getGuildId();
if (![ChannelTypes.GUILD_CATEGORY, ...GUILD_VOCAL_CHANNEL_TYPES].includes(a0.type)) {
r11.push(new Promise((c26766_0) => {
MessageStore.whenReady(a0.id, () => c26766_0());
MessageActionCreators.fetchMessages({
channelId: a0.id,
limit: MAX_MESSAGES_PER_CHANNEL
});
}));
}
return Promise.all(r11).then(() => {
let r4, messages;
L7: {
L5: {
r4 = a0;
if (r4.isNSFW()) {
if (UserStore.getCurrentUser()?.nsfwAllowed !== true) {
break L5;
}
}
if (c18160_1) {
messages = MessageStore.getMessages(r4.id).toArray().map(transformInternalTextMessage);
break L7;
}
}
messages = [];
}
return {
id: r4.id,
name: r4.name,
type: r4.type,
topic: r4.topic,
bitrate: r4.bitrate,
user_limit: r4.userLimit,
guild_id: guildId,
position: r4.position,
messages,
voice_states: Object.values(VoiceStateStore.getVoiceStatesForChannel(r4.id)).map((item) => {
const id = a0.id;
const { mute, deaf, selfMute, selfDeaf, suppress, userId } = item;
const user = UserStore.getUser(userId);
if (user == null) {
throw new Error(`Invalid user id: ${userId}`);
}
return {
nick: NicknameUtils.getName(guildId, id, user),
mute: MediaEngineStore.isLocalMute(user.id),
volume: MediaEngineStore.getLocalVolume(user.id),
pan: MediaEngineStore.getLocalPan(user.id),
voice_state: {
mute,
deaf,
self_mute: selfMute,
self_deaf: selfDeaf,
suppress
},
user: transformUser(user)
};
})
};
});
}
export { transformInternalTextMessage };
export function transformBaseRelationship(a0, a1) {
return {
type: a0,
user: transformUser(a1),
presence: {
status: PresenceStore.getStatus(a1.id, null),
activity: null
}
};
}
export function transformApplicationRelationship(a0, a1) {
let r1 = a0;
if (a1 != null) {
let activity = PresenceStore.getApplicationActivity(a0.user.id, a1);
if (activity == null) {
activity = null;
}
r1 = {
...a0,
presence: {
...a0.presence,
activity
}
};
}
return r1;
}
export function isMatchingOrigin(a0) {
let hostname;
if (a0 == null) {
return false;
}
const origin = window.location.origin;
if (a0 === origin) {
return true;
}
try {
hostname = Url.parse(a0).hostname;
} catch ($e) {
return false;
}
let r20 = window.location.hostname === hostname && hostname === "localhost";
if (!r20) {
let r26 = a0.match("staging") == null;
if (r26) {
const r29 = c7133_24.test(a0);
r26 = !(r29 ? !c7133_24.test(origin) : !r29);
}
r20 = r26;
}
return r20;
}
export function hasMessageReadPermission(a0, a1, a2) {
const guild = GuildStore.getGuild(a0.getGuildId());
return (guild != null ? guild.application_id : a0.getApplicationId()) === a1 || a2.indexOf(OAuth2Scopes.MESSAGES_READ) > -1;
}
export function getVoiceConnectionState(a0) {
if (RTCConnectionStates.RTC_CONNECTED !== a0 && RTCConnectionStates.RTC_CONNECTING !== a0 && RTCConnectionStates.RTC_DISCONNECTED !== a0) {
return a0;
}
return a0.replace(/^RTC_/, "VOICE_");
}
export function validateActivityInvite(a0, a1, a2) {
return a0 === ActivityActionTypes.JOIN && (a1 != null && a1.id != null && a2.join != null);
}
export async function validateSocketApplication(c26764_0, c26764_1, c26764_2) {
let createFromServer, c26764_4, c26764_5;
let c30270_0, c30270_1, c30270_2, c30270_3, c30270_4, c30270_5, c30270_6, c30270_7, c30270_8, c30270_9, c30270_10, c30270_11;
L17: {
L24: {
L16: {
L7: {
c26764_5 = void 0;
c30270_0 = c26764_0;
c30270_1 = c26764_1;
c30270_2 = c26764_2;
c30270_3 = void 0;
c30270_4 = void 0;
c30270_5 = void 0;
c30270_6 = void 0;
c30270_7 = void 0;
c30270_8 = void 0;
c30270_9 = void 0;
c30270_10 = void 0;
c30270_11 = void 0;
c30270_3 = ApplicationStore.getApplication(c26764_1);
if (typeof c26764_2 === "string") {
if (c26764_0.transport === TransportTypes.POST_MESSAGE) {
const uRLForApplication = getURLForApplication(c26764_1);
if (uRLForApplication != null && validateOrigin(c26764_2, [uRLForApplication])) {
break L7;
}
throw new RPCError({
closeCode: RPCCloseCodes.INVALID_ORIGIN
}, "Invalid Origin");
}
c30270_4 = await fetchApplicationRPC(c26764_1);
c30270_3 = ApplicationRecord.createFromServer(c30270_4);
if ((0, validateOrigin)(c30270_2, c30270_4.rpc_origins)) {
if (c30270_3 == null) {
c26764_4 = ApplicationRecord;
createFromServer = ApplicationRecord.createFromServer;
c30270_3 = createFromServer.call(c26764_4, await (0, fetchApplicationRPC)(c30270_1));
break L16;
}
break L16;
}
throw new RPCError({
closeCode: RPCCloseCodes.INVALID_ORIGIN
}, "Invalid Origin");
}
}
if (c30270_3 != null) {
c30270_5 = c30270_3;
c30270_6 = c30270_5.id;
c30270_7 = c30270_5.name;
c30270_8 = c30270_5.icon;
c30270_9 = c30270_5.coverImage;
c30270_10 = c30270_5.flags;
c30270_11 = c30270_5.parentId;
c30270_0.application = {
id: c30270_6,
parentId: c30270_11,
name: c30270_7,
icon: c30270_8,
coverImage: c30270_9,
flags: c30270_10
};
break L24;
}
c26764_4 = ApplicationRecord;
createFromServer = ApplicationRecord.createFromServer;
c30270_3 = createFromServer.call(c26764_4, await (0, fetchApplicationRPC)(c30270_1));
}
c30270_5 = c30270_3;
c30270_6 = c30270_5.id;
c30270_7 = c30270_5.name;
c30270_8 = c30270_5.icon;
c30270_9 = c30270_5.coverImage;
c30270_10 = c30270_5.flags;
c30270_11 = c30270_5.parentId;
c30270_0.application = {
id: c30270_6,
parentId: c30270_11,
name: c30270_7,
icon: c30270_8,
coverImage: c30270_9,
flags: c30270_10
};
break L17;
}
return void 0;
}
}
export async function processSocketThrottlers(c26765_0, c26765_1, c26765_2) {
let c26765_6 = 0;
try {
let r17 = c7133_26[c26765_0];
if (r17 == null) {
const r23 = 60;
if (!c26765_1) {
const leakyBucket = new LeakyBucket(r23, c7133_25);
c7133_26[c26765_0] = leakyBucket;
r17 = leakyBucket;
} else {
const leakyBucket2 = new LeakyBucket(2, c7133_25);
c7133_26[c26765_0] = leakyBucket2;
r17 = leakyBucket2;
}
}
c26765_6 = 1;
await r17.process(c26765_2);
c26765_6 = 0;
} catch ($e) {
let r8 = $e;
if (c26765_6 !== 0) {
while (true) {
try {
c26765_6 = 0;
throw new RPCError({
closeCode: RPCCloseCodes.CLOSE_ABNORMAL
}, "Socket closed during throttle");
} catch ($e) {
r8 = $e;
if (c26765_6 === 0) {
break;
}
}
}
}
throw r8;
}
}
export function validateOriginAndUpdateSocket(a0, a1) {
if (a1 == null) {
a0.authorization.scopes = [RPC_LOCAL_SCOPE];
}
}
export function getDeprecatedVoiceSettingsWithShortcut(a0) {
const settings = MediaEngineStore.getSettings();
const shortcut = a0(settings);
return {
input: {
available_devices: Object.values(MediaEngineStore.getInputDevices()).sort($mk107395()).map($mk107396()),
device_id: settings.inputDeviceId,
volume: settings.inputVolume
},
output: {
available_devices: Object.values(MediaEngineStore.getOutputDevices()).sort($mk107395()).map($mk107396()),
device_id: settings.outputDeviceId,
volume: settings.outputVolume
},
mode: {
type: settings.mode,
auto_threshold: settings.modeOptions.autoThreshold,
threshold: settings.modeOptions.threshold,
shortcut,
delay: settings.modeOptions.delay
},
automatic_gain_control: settings.automaticGainControl,
echo_cancellation: settings.echoCancellation,
noise_suppression: settings.noiseSuppression,
qos: settings.qos,
silence_warning: settings.silenceWarning,
deaf: settings.deaf,
mute: settings.mute
};
}
export function getVoiceSettingsWithShortcut(a0, a1) {
const settings = MediaEngineStore.getSettings(a0);
return {
input_mode: {
type: settings.mode,
shortcut: a1(settings)
},
local_mutes: Object.keys(settings.localMutes),
local_volumes: settings.localVolumes,
self_mute: settings.mute,
self_deaf: settings.deaf
};
}
export function validatePostMessageTransport(a0) {
if (a0 !== TransportTypes.POST_MESSAGE) {
throw new RPCError({
errorCode: RPCErrors.INVALID_COMMAND
}, `command not available from "${a0} transport`);
}
}
export function validateApplication(a0) {
if (a0.id == null) {
throw new RPCError({
errorCode: RPCErrors.INVALID_COMMAND
}, "Invalid application");
}
return a0.id;
}