This commit is contained in:
janisslsm committed 2026-11-01 12:12:55 +02:00
1 parent 1781d25a15
commit 732c0ad767
33051 files changed
+2591613 -3019689

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
// Metro module 12707 (f12708).
import Dispatcher from "../../Dispatcher";
class ActionBatcher {
static batchers = [];
constructor(a0, c19988_0, a2) {
this.action = null;
this.socket = a0;
this.shouldFlush = a2;
this.add = (a0) => {
this.action = c19988_0(this.action, a0);
};
ActionBatcher.batchers.push(this);
}
static flush(a0, a1) {
for (const batcher of ActionBatcher.batchers) {
const r28 = batcher;
if (batcher.action != null && (a0 == null || r28.shouldFlush(a0, a1))) {
r28.flush();
}
}
}
flush() {
const action = this.action;
this.action = null;
if (action != null) {
Dispatcher.dispatch(action).catch((a0) => this.socket.resetSocketAndClearCacheOnError({
error: a0,
action: action.type
}));
}
}
}
export default ActionBatcher;
+42
View File
@@ -0,0 +1,42 @@
// Metro module 12698 (f12699).
import getCachedUseAltGateway_native from "./getCachedUseAltGateway.native";
const GATEWAY_ALT_ENDPOINT = window.GLOBAL_ENV.GATEWAY_ALT_ENDPOINT;
let c8748_1 = getCachedUseAltGateway_native();
class AltGatewayTracker {
constructor() {
return {
__proto__: new.target.prototype,
failures: 0,
fallbackTripped: false
};
}
shouldUseAltGateway() {
const fallbackTripped = this.fallbackTripped;
return (fallbackTripped ? !fallbackTripped : GATEWAY_ALT_ENDPOINT != null) && c8748_1;
}
isAssignedToAltGateway() {
return GATEWAY_ALT_ENDPOINT != null && c8748_1;
}
getDidFallBack() {
return this.fallbackTripped;
}
getAltGatewayUrl() {
return this.shouldUseAltGateway() ? GATEWAY_ALT_ENDPOINT : null;
}
recordSuccess() {
this.failures = 0;
}
recordFailure() {
if (this.shouldUseAltGateway()) {
this.failures = this.failures + 1;
if (this.failures >= 3) {
this.fallbackTripped = true;
}
}
}
reset() {
this.failures = 0;
this.fallbackTripped = false;
}
}
export default AltGatewayTracker;
+123
View File
@@ -0,0 +1,123 @@
// Metro module 12703 (f12704).
import { DISPATCHER_IDEAL_TIME_LIMIT_MS, DISPATCHER_LONG_TIMEOUT_MS, DISPATCHER_STANDARD_TIMEOUT_MS, MAX_DISPATCHER_FLUSH_DEADLINE_TRIES } from "./DispatcherWorkConstants";
import Logger from "../debug/Logger";
import { WorkSchedulerTelemetry, WorkSchedulerTelemetryEvent, WorkSchedulerTelemetryMeasurement, WorkSchedulerTelemetryTiming } from "./WorkSchedulerTelemetry";
import Module38 from "../../_bundle/Module38";
const _logger = new Logger("DispatcherWorkScheduler");
export class BasicWorkScheduler {
constructor() {
return {
__proto__: new.target.prototype,
_flushTimeoutHandler: null,
_flushIdleHandler: null,
_nextDispatchTimeout: DISPATCHER_STANDARD_TIMEOUT_MS,
_workCallbackFn: null,
_consecutiveFlushesBeforeQueueEmpty: 0,
_isBackgrounded: false,
_enableRequestIdleCallback: true,
_criticalWorkScheduled: false,
telemetry: new WorkSchedulerTelemetry(),
_logger
};
}
_trackAppBackgrounded(a0) {
if (this._isBackgrounded !== a0) {
this._isBackgrounded = a0;
if (this._isBackgrounded && this.hasWorkScheduled) {
this.telemetry.track(WorkSchedulerTelemetryEvent.SKIP_IDLE_CALLBACK_DUE_TO_BACKGROUNDED);
this._processWorkCallback();
}
}
}
_queueIdleCallback() {
throw new Error("Not implemented");
}
_clearIdleCallback() {
throw new Error("Not implemented");
}
get _hasExceededMaxConsecutiveFlushes() {
return this._consecutiveFlushesBeforeQueueEmpty >= MAX_DISPATCHER_FLUSH_DEADLINE_TRIES;
}
_processWorkCallback(a0) {
if (this._workCallbackFn != null) {
if (this._hasExceededMaxConsecutiveFlushes) {
_logger.log("Unable to fully flush work queue after max retries, skipping future deadline.");
this._workCallbackFn();
this.clearWorkTimeout();
this.telemetry.measure(WorkSchedulerTelemetryMeasurement.COUNT_FLUSH_BEFORE_QUEUE_EMPTY, this._consecutiveFlushesBeforeQueueEmpty);
this.telemetry.track(WorkSchedulerTelemetryEvent.EXCEEDED_MAX_CONSECUTIVE_FLUSHES);
this._consecutiveFlushesBeforeQueueEmpty = 0;
this._nextDispatchTimeout = DISPATCHER_LONG_TIMEOUT_MS;
return void 0;
}
const r13 = performance.now();
const r15 = this._workCallbackFn(a0);
const r17 = performance.now();
this.clearWorkTimeout();
this._nextDispatchTimeout = r17 - r13 > DISPATCHER_IDEAL_TIME_LIMIT_MS ? DISPATCHER_LONG_TIMEOUT_MS : DISPATCHER_STANDARD_TIMEOUT_MS;
const _consecutiveFlushesBeforeQueueEmpty = this._consecutiveFlushesBeforeQueueEmpty;
if (r15) {
if (_consecutiveFlushesBeforeQueueEmpty > 0) {
this.telemetry.measure(WorkSchedulerTelemetryMeasurement.COUNT_FLUSH_BEFORE_QUEUE_EMPTY, parseInt(`${this._consecutiveFlushesBeforeQueueEmpty}`));
}
this._consecutiveFlushesBeforeQueueEmpty = 0;
this._criticalWorkScheduled = false;
} else {
this._consecutiveFlushesBeforeQueueEmpty = _consecutiveFlushesBeforeQueueEmpty + 1;
}
}
}
markCriticalWorkScheduled() {
this._criticalWorkScheduled = true;
if (this._flushIdleHandler != null) {
this._clearIdleCallback();
this._processWorkCallback();
}
}
toggleRequestIdleCallback(a0) {
this._enableRequestIdleCallback = a0;
if (a0 ? !a0 : this.hasWorkScheduled) {
this._clearIdleCallback();
this._processWorkCallback();
}
}
get isBackgrounded() {
return this._isBackgrounded;
}
get hasWorkScheduled() {
return this._flushTimeoutHandler != null || this._flushIdleHandler != null;
}
get isRequestIdleCallbackEnabled() {
return this._enableRequestIdleCallback;
}
clearWorkTimeout() {
if (this._flushTimeoutHandler != null) {
clearTimeout(this._flushTimeoutHandler);
this._flushTimeoutHandler = null;
}
this._clearIdleCallback();
this._nextDispatchTimeout = DISPATCHER_STANDARD_TIMEOUT_MS;
this._workCallbackFn = null;
}
requestWorkTimeout(a0, r4 = false) {
this._workCallbackFn = a0;
if (!this.hasWorkScheduled) {
this.telemetry.time(WorkSchedulerTelemetryTiming.TIME_TO_QUEUE_EMPTY);
if (this._nextDispatchTimeout === DISPATCHER_LONG_TIMEOUT_MS) {
this.telemetry.track(WorkSchedulerTelemetryEvent.LONGER_DISPATCH);
}
if (r4) {
this._queueIdleCallback();
} else {
this._flushTimeoutHandler = setTimeout(() => {
Module38(this._workCallbackFn != null, "Work callback should be set");
if (this._isBackgrounded) {
this.telemetry.track(WorkSchedulerTelemetryEvent.SKIP_IDLE_CALLBACK_DUE_TO_BACKGROUNDED);
return this._processWorkCallback();
}
this._queueIdleCallback();
}, this._nextDispatchTimeout);
}
}
}
}
+486
View File
@@ -0,0 +1,486 @@
// Metro module 16149 (f16150).
import AuthenticationStore from "../../stores/AuthenticationStore";
import ChannelStore from "../../stores/ChannelStore";
import GuildAvailabilityStore from "../../stores/GuildAvailabilityStore";
import GuildStore from "../../stores/GuildStore";
import GatewayConnectionStore from "./GatewayConnectionStore";
import { AnalyticEvents } from "../../Constants";
import { ChannelFlags } from "../channel/ChannelConstants";
import Logger from "../debug/Logger";
import Durations from "../../utils/Durations";
import AutomaticLifecycleManager from "../../lib/AutomaticLifecycleManager";
import AnalyticsUtils from "../../utils/AnalyticsUtils";
import Dispatcher from "../../Dispatcher";
import GuildsRequiringChannelSync from "../app_database/modules/GuildsRequiringChannelSync";
import { isChannelMetadataIntegrityCheckEnabled } from "./PrivateChannelHidingExperiment";
import * as _Module1384 from "../../_bundle/Module1384";
import { v4 } from "../../_bundle/Module514";
function $mk117190($env) {
return (a0) => {
const r6 = $env[0];
if (!(r6 != null && a0.id !== r6)) {
const { id, requestId } = a0;
let env31790 = {
$parent: $env.$parent
};
env31790[0] = id;
c11570_17[id] = {
guildId: id,
requestId,
source: "resync",
requestedUserId: AuthenticationStore.getId()
};
if (c11570_19[id] != null) {
clearTimeout(c11570_19[id]);
}
c11570_19[id] = setTimeout(() => {
let r1;
const r12 = env31790.$parent;
const r11 = r12[19];
const guild_id3 = env31790[0];
delete r11[guild_id3];
const r15 = r12[0];
const r13 = r12[2];
if (r15(r13[14]).isChannelMetadataObfuscationEnabled("triggerGuildChannelResync")) {
let request_id2 = r12[17][guild_id3]?.requestId;
if (request_id2 == null) {
request_id2 = "unknown";
}
if (r12[7].getGuild(guild_id3) == null) {
(0, r12[1])(r13[11]).track(r12[9].GUILD_CHANNEL_RESYNC_FAILED, {
guild_id: guild_id3,
request_id: request_id2,
failure_reason: "guild_not_found"
});
const r85 = r12[20];
if (r85[guild_id3] != null) {
clearTimeout(r85[guild_id3]);
delete r85[guild_id3];
}
if (r11[guild_id3] != null) {
clearTimeout(r11[guild_id3]);
delete r11[guild_id3];
}
} else {
const r35 = [];
const mutableGuildChannelsForGuild2 = r12[5].getMutableGuildChannelsForGuild(guild_id3);
let r0 = 0;
let num_total_channels = 0;
for (const key in mutableGuildChannelsForGuild2) {
r1 = r0;
num_total_channels = r1;
const r20 = mutableGuildChannelsForGuild2[key];
if ((0, r12[0])(r12[2][15]).hasFlag(r20.flags, r12[10].OBFUSCATED)) {
r35.push(key);
}
r0 = r1 + 1;
}
r1 = r0;
num_total_channels = r1;
(0, r12[1])(r12[2][11]).track(r12[9].GUILD_CHANNEL_RESYNC_EXECUTED, {
guild_id: guild_id3,
request_id: request_id2,
num_obfuscated_channels: r35.length,
num_total_channels
});
r12[8].getSocket().triggerGuildChannelResync(guild_id3, r35);
let env32145 = {
$parent: r12
};
env32145[0] = guild_id3;
env32145[1] = request_id2;
const r64 = r12[20];
if (r64[guild_id3] != null) {
clearTimeout(r64[guild_id3]);
}
r64[guild_id3] = setTimeout(() => {
const guild_id3 = env32145[0];
const request_id2 = env32145[1];
const r12 = env32145.$parent;
r12[11].warn(`Resync timeout for guild ${guild_id3} with request ${request_id2}`);
(0, r12[1])(r12[2][11]).track(r12[9].GUILD_CHANNEL_RESYNC_FAILED, {
guild_id: guild_id3,
request_id: request_id2,
failure_reason: "timeout"
});
const r25 = r12[20];
if (r25[guild_id3] != null) {
clearTimeout(r25[guild_id3]);
delete r25[guild_id3];
}
const r30 = r12[19];
if (r30[guild_id3] != null) {
clearTimeout(r30[guild_id3]);
delete r30[guild_id3];
}
}, r12[15]);
(0, r12[32])(guild_id3);
}
}
}, Math.ceil(Math.random() * c11570_12));
}
};
}
function $mk117192($env) {
return (a0, a1) => {
if (GuildStore.getGuild(a1.id) == null && !GuildAvailabilityStore.isUnavailable(a1.id)) {
a0.ineligible.push(a1);
} else {
a0.eligible.push(a1);
}
return a0;
};
}
let handlePostConnectionOpen, handleChannelSync, handleLogout, scheduleGuildResyncs, scheduleIntegrityCheck, c11570_11, c11570_12, c11570_13, c11570_14, c11570_15, c11570_16, c11570_33, c11570_17, c11570_18, c11570_19, c11570_20, c11570_21, c11570_22, c11570_23;
let env11570 = {};
const handleGuildCreate = function handleGuildCreate({ guild }) {
let c22823_1;
c22823_1 = void 0;
if (guild.unavailable !== true) {
if (c11570_23[guild.id] != null) {
clearTimeout(c11570_23[guild.id]);
}
c22823_1 = env11570[24];
c11570_23[guild.id] = setTimeout(() => {
delete c11570_23[guild.id];
if (c22823_1 === env11570[24]) {
c11570_18.delete(guild.id);
scheduleGuildResyncs(guild.id);
scheduleIntegrityCheck(guild.id);
}
}, 0);
}
};
handlePostConnectionOpen = function handlePostConnectionOpen() {
c11570_18.clear();
scheduleGuildResyncs();
GuildStore.getGuildIds().forEach((item) => {
scheduleIntegrityCheck(item);
});
};
handleChannelSync = function handleChannelSync(a0) {
const { integrity_check, guild_id: guild_id3 } = a0;
if (integrity_check) {
const channels = a0.channels;
let request_id3 = c11570_17[guild_id3]?.requestId;
if (request_id3 == null) {
request_id3 = "unknown";
}
const mutableGuildChannelsForGuild = ChannelStore.getMutableGuildChannelsForGuild(guild_id3);
const set = new Set();
let c22824_1 = set;
const r61 = [];
let c22824_2 = r61;
channels.forEach((channel) => {
const r7 = mutableGuildChannelsForGuild[channel.id];
if (r7 != null) {
let flags = channel.flags;
if (flags == null) {
flags = 0;
}
const hasFlag = _Module1384.hasFlag(flags, ChannelFlags.OBFUSCATED);
const hasFlag2 = _Module1384.hasFlag(r7.flags, ChannelFlags.OBFUSCATED);
if (hasFlag !== hasFlag2) {
c11570_11.warn(`Integrity check failure: ${channel.id} serverObfuscated: ${hasFlag} != clientObfuscated: ${hasFlag2}`);
c22824_1.add(channel.id);
let flags2 = channel.flags;
if (flags2 == null) {
flags2 = 0;
}
let flags3 = r7.flags;
if (flags3 == null) {
flags3 = 0;
}
let parent_id = channel.parent_id;
if (parent_id == null) {
parent_id = null;
}
c22824_2.push({
channel_id: channel.id,
server_obfuscated: hasFlag,
client_obfuscated: hasFlag2,
server_flags: flags2,
client_flags: flags3,
channel_type: channel.type,
parent_id
});
}
} else {
c11570_11.warn(`Integrity check failure: ${channel.id} was missing.`);
}
});
const discrepancy_channel_ids = Array.from(set).join(", ");
const discrepancies_details = r61.length > 0 ? JSON.stringify(r61) : null;
(set.size > 0 ? c11570_11.warn : c11570_11.verbose)(`Integrity check for guild ${guild_id3} completed. Discrepancies found: ${discrepancy_channel_ids}`);
AnalyticsUtils.track(AnalyticEvents.GUILD_CHANNEL_INTEGRITY_CHECK_COMPLETED, {
guild_id: guild_id3,
request_id: request_id3,
num_channels_received: channels.length,
num_discrepancies_found: set.size,
discrepancy_channel_ids,
discrepancies_details
});
if (c11570_22[guild_id3] != null) {
clearTimeout(c11570_22[guild_id3]);
delete c11570_22[guild_id3];
}
if (c11570_21[guild_id3] != null) {
clearTimeout(c11570_21[guild_id3]);
delete c11570_21[guild_id3];
}
c11570_18.add(guild_id3);
} else {
let request_id2 = c11570_17[guild_id3]?.requestId;
if (request_id2 == null) {
request_id2 = "unknown";
}
AnalyticsUtils.track(AnalyticEvents.GUILD_CHANNEL_RESYNC_COMPLETED, {
guild_id: a0.guild_id,
request_id: request_id2,
num_new_channels: a0.channels.length
});
const guild_id4 = a0.guild_id;
if (c11570_20[guild_id4] != null) {
clearTimeout(c11570_20[guild_id4]);
delete c11570_20[guild_id4];
}
if (c11570_19[guild_id4] != null) {
clearTimeout(c11570_19[guild_id4]);
delete c11570_19[guild_id4];
}
scheduleIntegrityCheck(a0.guild_id);
}
};
handleLogout = function handleLogout(a0) {
env11570[24] = env11570[24] + 1;
const cancellation_reason = a0.isSwitchingAccount === true ? "account_switch" : "logout";
const set = new Set([...Object.keys(c11570_19), ...Object.keys(c11570_20), ...Object.keys(c11570_21), ...Object.keys(c11570_22)]);
set.forEach((item) => {
const r9 = c11570_17[item];
if (r9 != null) {
const had_scheduled_timer = c11570_19[item] != null;
const had_pending_timeout = c11570_20[item] != null;
if (had_scheduled_timer || had_pending_timeout) {
const GUILD_CHANNEL_RESYNC_CANCELED = AnalyticEvents.GUILD_CHANNEL_RESYNC_CANCELED;
let requestedUserId = r9.requestedUserId;
if (requestedUserId == null) {
requestedUserId = null;
}
AnalyticsUtils.track(GUILD_CHANNEL_RESYNC_CANCELED, {
guild_id: item,
request_id: r9.requestId,
requested_user_id: requestedUserId,
cancellation_reason,
had_scheduled_timer,
had_pending_timeout
});
}
const had_scheduled_timer2 = c11570_21[item] != null;
const had_pending_timeout2 = c11570_22[item] != null;
if (had_scheduled_timer2 || had_pending_timeout2) {
const GUILD_CHANNEL_INTEGRITY_CHECK_CANCELED = AnalyticEvents.GUILD_CHANNEL_INTEGRITY_CHECK_CANCELED;
let requestedUserId2 = r9.requestedUserId;
if (requestedUserId2 == null) {
requestedUserId2 = null;
}
AnalyticsUtils.track(GUILD_CHANNEL_INTEGRITY_CHECK_CANCELED, {
guild_id: item,
request_id: r9.requestId,
requested_user_id: requestedUserId2,
cancellation_reason,
had_scheduled_timer: had_scheduled_timer2,
had_pending_timeout: had_pending_timeout2
});
}
}
});
set.forEach((item) => {
if (c11570_20[item] != null) {
clearTimeout(c11570_20[item]);
delete c11570_20[item];
}
if (c11570_19[item] != null) {
clearTimeout(c11570_19[item]);
delete c11570_19[item];
}
if (c11570_22[item] != null) {
clearTimeout(c11570_22[item]);
delete c11570_22[item];
}
if (c11570_21[item] != null) {
clearTimeout(c11570_21[item]);
delete c11570_21[item];
}
});
for (const key in c11570_23) {
const r12 = clearTimeout;
r12(c11570_23[key]);
delete c11570_23[key];
}
for (const key2 in c11570_17) {
delete c11570_17[key2];
}
c11570_18.clear();
};
scheduleGuildResyncs = async function scheduleGuildResyncs(c28243_0) {
let env30966;
const r9 = env11570;
let c28243_2 = r9;
const r12 = env30966 = {
$parent: r9
};
let c28243_1 = r12;
env30966[0] = c28243_0;
env30966[2] = void 0;
env30966[3] = void 0;
env30966[1] = env11570[24];
const r35 = await (function getResyncGuilds() {
return env11570[31].apply(this, arguments);
})();
env30966[2] = r35;
if (env30966[1] === env11570[24]) {
c11570_11.verbose(`Resync guilds: ${JSON.stringify(env30966[2])}`);
env30966[2].eligible.forEach($mk117190(c28243_1));
if (env30966[2].ineligible.length > 0) {
env30966[3] = env30966[2].ineligible.map((item) => item.id);
c11570_11.verbose(`Guilds we are no longer part of are marked for resync. Unmarking them. Guilds: ${JSON.stringify(env30966[3])}`);
Dispatcher.dispatch({
type: "UNMARK_RESYNC_GUILDS",
guildIds: env30966[3]
});
}
}
};
env11570[31] = function _getResyncGuilds() {
const r8 = async () => {
let c28244_0 = env11570;
return (await GuildsRequiringChannelSync.getAll()).reduce($mk117192(c28244_0), {
eligible: [],
ineligible: []
});
};
env11570[31] = r8;
return r8.apply(this, arguments);
};
scheduleIntegrityCheck = function scheduleIntegrityCheck(a0) {
let requestId;
const guild_id = a0;
if (isChannelMetadataIntegrityCheckEnabled("scheduleIntegrityCheck")) {
const r2 = c11570_21[a0] != null;
if (c11570_22[a0] != null) {
clearTimeout(c11570_22[a0]);
delete c11570_22[a0];
}
if (c11570_21[a0] != null) {
clearTimeout(c11570_21[a0]);
delete c11570_21[a0];
}
const r32 = c11570_17[a0];
if (r32 != null) {
requestId = r32.requestId;
} else {
const requestId2 = v4();
c11570_17[a0] = {
guildId: a0,
requestId: requestId2,
source: "integrity_check",
requestedUserId: AuthenticationStore.getId()
};
requestId = requestId2;
}
if (!r2) {
AnalyticsUtils.track(AnalyticEvents.GUILD_CHANNEL_INTEGRITY_CHECK_REQUESTED, {
guild_id: a0,
request_id: requestId
});
}
c11570_21[a0] = setTimeout(() => {
delete c11570_21[guild_id];
if (isChannelMetadataIntegrityCheckEnabled("triggerIntegrityCheck") && !c11570_18.has(guild_id)) {
let request_id2 = c11570_17[guild_id]?.requestId;
if (request_id2 == null) {
request_id2 = "unknown";
}
if (GuildStore.getGuild(guild_id) == null) {
AnalyticsUtils.track(AnalyticEvents.GUILD_CHANNEL_INTEGRITY_CHECK_FAILED, {
guild_id,
request_id: request_id2,
failure_reason: "guild_not_found"
});
if (c11570_22[guild_id] != null) {
clearTimeout(c11570_22[guild_id]);
delete c11570_22[guild_id];
}
if (c11570_21[guild_id] != null) {
clearTimeout(c11570_21[guild_id]);
delete c11570_21[guild_id];
}
} else {
AnalyticsUtils.track(AnalyticEvents.GUILD_CHANNEL_INTEGRITY_CHECK_EXECUTED, {
guild_id,
request_id: request_id2
});
GatewayConnectionStore.getSocket().triggerGuildChannelResync(guild_id, null);
const guild_id2 = guild_id;
const request_id = request_id2;
if (c11570_22[guild_id] != null) {
clearTimeout(c11570_22[guild_id]);
}
c11570_22[guild_id] = setTimeout(() => {
c11570_11.warn(`Integrity check timeout for guild ${guild_id2} with request ${request_id}`);
AnalyticsUtils.track(AnalyticEvents.GUILD_CHANNEL_INTEGRITY_CHECK_FAILED, {
guild_id: guild_id2,
request_id,
failure_reason: "timeout"
});
if (c11570_22[guild_id2] != null) {
clearTimeout(c11570_22[guild_id2]);
delete c11570_22[guild_id2];
}
if (c11570_21[guild_id2] != null) {
clearTimeout(c11570_21[guild_id2]);
delete c11570_21[guild_id2];
}
}, c11570_16);
}
}
}, c11570_13 + Math.ceil(Math.random() * c11570_14));
}
};
c11570_11 = new Logger("ChannelResyncManager");
c11570_12 = 2 * Durations.Millis.SECOND;
c11570_13 = 30 * Durations.Millis.SECOND;
c11570_14 = 300 * Durations.Millis.SECOND;
c11570_15 = 30 * Durations.Millis.SECOND;
c11570_16 = 60 * Durations.Millis.SECOND;
class ChannelResyncManager extends AutomaticLifecycleManager {
actions = {
GUILD_CREATE: handleGuildCreate,
POST_CONNECTION_OPEN: handlePostConnectionOpen,
CHANNEL_SYNC: handleChannelSync,
LOGOUT: handleLogout
};
__unsafeGetTestState() {
return {
scheduledResyncTimerGuildIds: Object.keys(c11570_19),
pendingResyncTimeoutGuildIds: Object.keys(c11570_20),
scheduledIntegrityCheckTimerGuildIds: Object.keys(c11570_21),
pendingIntegrityCheckTimeoutGuildIds: Object.keys(c11570_22),
pendingGuildCreateDeferredGuildIds: Object.keys(c11570_23),
guildIdsWithLatestRequest: Object.keys(c11570_17),
guildsCompletedIntegrityCheck: Array.from(c11570_18),
sessionEpoch: env11570[24]
};
}
}
c11570_33 = ChannelResyncManager;
c11570_17 = {};
c11570_18 = new Set();
c11570_19 = {};
c11570_20 = {};
c11570_21 = {};
c11570_22 = {};
c11570_23 = {};
env11570[24] = 0;
const r96 = new ChannelResyncManager();
export default r96;
+10
View File
@@ -0,0 +1,10 @@
// Metro module 12706 (f12707).
const r8 = {
CLOSED: "CLOSED",
WILL_RECONNECT: "WILL_RECONNECT",
CONNECTING: "CONNECTING",
IDENTIFYING: "IDENTIFYING",
RESUMING: "RESUMING",
SESSION_ESTABLISHED: "SESSION_ESTABLISHED"
};
export default r8;
@@ -0,0 +1,36 @@
// Metro module 12701 (f12702).
let c8751_0 = 2.0833333333333335;
export const DISPATCHER_STANDARD_TIMEOUT_MS = 50;
export const DISPATCHER_IDEAL_TIME_LIMIT_MS = 50;
export const DISPATCHER_MIN_DEADLINE_TIME_MS = 2.0833333333333335;
export const DISPATCHER_DEADLINE_OVERHEAD_MS = 3.3333333333333335;
export const NATIVE_WORK_DEADLINE_MS = 5.555555555555556;
export const NATIVE_WORK_BACKOFF_MS = 4.166666666666667;
export const DISPATCHER_LONG_TIMEOUT_MS = 200;
export const MAX_DISPATCHER_TIMEOUT_MS = 1000;
export const MAX_DISPATCHER_FLUSH_DEADLINE_TRIES = 2;
export const DISPATCHER_CALLBACK_MAX_TIME_REMAINING_MS = 50;
export class WorkIdleDeadline {
constructor(a0, _firedDueToMaxTimeout = false) {
this._deadlineMs = Math.max(c8751_0, a0);
this._browserDeadlineMs = a0;
this._firedDueToMaxTimeout = _firedDueToMaxTimeout;
this._startMs = performance.now();
}
timeRemaining() {
return Math.max(0, this._deadlineMs - (performance.now() - this._startMs));
}
get didTimeout() {
return this._firedDueToMaxTimeout;
}
get timeSinceExpiration() {
return performance.now() - (this._startMs + this._deadlineMs);
}
generateDeadlineMetrics() {
return {
isDeadlineNotIdeal: this._browserDeadlineMs < c8751_0,
deadlineMs: this._deadlineMs.toFixed(2),
timeSinceStartMs: (performance.now() - this._startMs).toFixed(2)
};
}
}
@@ -0,0 +1,60 @@
// Metro module 12702 (f12703).
import { WorkIdleDeadline, NATIVE_WORK_DEADLINE_MS, NATIVE_WORK_BACKOFF_MS, DISPATCHER_CALLBACK_MAX_TIME_REMAINING_MS } from "./DispatcherWorkConstants";
import "../../Constants";
import { BasicWorkScheduler } from "./BasicWorkScheduler";
import Dispatcher from "../../Dispatcher";
import { $callWithNewTarget } from "../../_hermes/prelude";
function $mk90274($env) {
return (a0) => {
$env[0]._trackAppBackgrounded(a0.state === $env.$parent[6].BACKGROUND);
};
}
let c8752_8, c8752_7;
let env8752 = {};
class DispatcherWorkScheduler extends BasicWorkScheduler {
constructor() {
let env19982;
const r2 = env19982 = {
$parent: env8752
};
env19982[0] = void 0;
super();
env19982[0] = this;
Dispatcher.subscribe("APP_STATE_UPDATE", $mk90274(r2));
}
_queueIdleCallback() {
let c19983_0;
if (this._enableRequestIdleCallback && !this._criticalWorkScheduled) {
c19983_0 = performance.now();
this._flushIdleHandler = setTimeout(() => {
const r9 = performance.now() - c19983_0;
const _consecutiveFlushesBeforeQueueEmpty = this._consecutiveFlushesBeforeQueueEmpty;
this._processWorkCallback(new WorkIdleDeadline(Math.max(Math.max(0, NATIVE_WORK_DEADLINE_MS - r9) + NATIVE_WORK_BACKOFF_MS * _consecutiveFlushesBeforeQueueEmpty, DISPATCHER_CALLBACK_MAX_TIME_REMAINING_MS), false));
}, 1);
return void 0;
}
return this._processWorkCallback();
}
_clearIdleCallback() {
if (this._flushIdleHandler != null) {
clearTimeout(this._flushIdleHandler);
this._flushIdleHandler = null;
}
}
}
c8752_8 = DispatcherWorkScheduler;
c8752_7 = DispatcherWorkScheduler;
export function createDispatcherWorkScheduler() {
let env19984;
const r2 = env19984 = {
$parent: env8752
};
env19984[0] = void 0;
const prototypeOf = Object.getPrototypeOf(c8752_8);
const r5 = Object.create(c8752_7.prototype);
const r13 = $callWithNewTarget(prototypeOf, r5, c8752_7);
const r14 = r13 instanceof Object ? r13 : r5;
env19984[0] = r14;
Dispatcher.subscribe("APP_STATE_UPDATE", $mk90274(r2));
return r14;
}
+150
View File
@@ -0,0 +1,150 @@
// Metro module 16165 (f16166).
import EmojiStore from "../emojis/EmojiStore";
import StickersStore from "../stickers/StickersStore";
import ChannelStore from "../../stores/ChannelStore";
import GuildRoleStore from "../../stores/GuildRoleStore";
import GuildStore from "../../stores/GuildStore";
import "./GatewayConnectionStore";
import Logger from "../debug/Logger";
import AutomaticLifecycleManager from "../../lib/AutomaticLifecycleManager";
import Dispatcher from "../../Dispatcher";
import Module589 from "../../_bundle/Module589";
import GuildsRequiringDeletedIdsSync from "../app_database/modules/GuildsRequiringDeletedIdsSync";
import SnowflakeUtils from "../../utils/SnowflakeUtils";
function $mk98825($env) {
return () => {
const r9 = $env[0];
const r21 = $env.$parent;
r21[8].fileOnly(`requesting deleted guild entities (id: ${r9}, name: ${r21[6].getGuild(r9)?.name})`);
const r10 = Object.keys(r21[4].getMutableBasicGuildChannelsForGuild(r9));
const r32 = r21[0];
const r33 = r21[1];
const r43 = r32(r33[11]).v3(r10.sort().join(",")).toString();
const r49 = r21[5].getSortedRoles(r9).map((item) => item.id);
const r59 = r32(r33[11]).v3(r49.sort().join(",")).toString();
const r13 = r21[2].getGuildEmoji(r9).map((item) => item.id);
const r74 = r32(r33[11]).v3(r13.sort().join(",")).toString();
const stickersByGuildId = r21[3].getStickersByGuildId(r9);
let r78 = stickersByGuildId == null ? void 0 : stickersByGuildId.map((item) => item.id);
if (r78 == null) {
r78 = [];
}
const r15 = r32(r33[11]).v3(r78.sort().join(",")).toString();
r21[7].getSocket().getDeletedEntityIdsNotMatchingHash(r9, r43, r59, r74, r15);
};
}
let handleConnectionOpen, handleGuildCreate, c11583_8, c11583_12;
let env11583 = {};
const handleDeletedEntityIds = function handleDeletedEntityIds(a0) {
c11583_8.fileOnly(`received deleted guild entities (id: ${a0.guild_id}, name: ${GuildStore.getGuild(a0.guild_id)?.name})`);
Module589.Emitter.batched(() => {
if (a0.channels != null) {
const guild_id3 = a0.guild_id;
const set = new Set(a0.channels);
const guild_id = guild_id3;
let c28247_1 = set;
const channelIdsInMemory = SnowflakeUtils.keys(ChannelStore.getMutableBasicGuildChannelsForGuild(guild_id));
c11583_8.fileOnly("syncChannels", {
channelIdsInMemory,
channelIdsFromServer: set
});
channelIdsInMemory.forEach((item) => {
if (!c28247_1.has(item)) {
Dispatcher.dispatch({
type: "CHANNEL_DELETE",
channel: {
guild_id,
id: item,
parent_id: void 0
}
});
}
});
}
if (a0.roles != null) {
const guild_id4 = a0.guild_id;
const set2 = new Set(a0.roles);
const guild_id2 = guild_id4;
let c28248_1 = set2;
SnowflakeUtils.keys(GuildRoleStore.getUnsafeMutableRoles(guild_id2)).forEach((item) => {
if (!c28248_1.has(item)) {
Dispatcher.dispatch({
type: "GUILD_ROLE_DELETE",
guildId: guild_id2,
roleId: item
});
}
});
}
if (a0.emojis != null) {
const guild_id5 = a0.guild_id;
let c28249_0 = new Set(a0.emojis);
const guildEmoji = EmojiStore.getGuildEmoji(guild_id5);
const emojis = guildEmoji.filter((item) => c28249_0.has(item.id));
if (guildEmoji.length !== emojis.length) {
Dispatcher.dispatch({
type: "GUILD_EMOJIS_UPDATE",
guildId: guild_id5,
emojis
});
}
}
if (a0.stickers != null) {
const guild_id6 = a0.guild_id;
let c28250_0 = new Set(a0.stickers);
let r97 = StickersStore.getStickersByGuildId(guild_id6);
if (r97 == null) {
r97 = [];
}
const stickers = r97.filter((item) => c28250_0.has(item.id));
if (r97.length !== stickers.length) {
Dispatcher.dispatch({
type: "GUILD_STICKERS_UPDATE",
guildId: guild_id6,
stickers
});
}
}
});
};
handleConnectionOpen = function handleConnectionOpen() {
GuildsRequiringDeletedIdsSync.getAll().then((result) => {
result.forEach((item) => {
let env30967;
const r2 = env30967 = {
$parent: env11583
};
env30967[0] = item;
const r11 = Math.ceil(2000 * Math.random());
setTimeout($mk98825(r2), r11);
});
});
};
handleGuildCreate = function handleGuildCreate({ guild }) {
if (guild.unableToSyncDeletes) {
let env22834;
const id = guild.id;
const r10 = env22834 = {
$parent: env11583
};
env22834[0] = id;
const r14 = Math.ceil(2000 * Math.random());
setTimeout($mk98825(r10), r14);
}
};
c11583_8 = new Logger("EntityVersionsManager");
class EntityVersionsManager extends AutomaticLifecycleManager {
actions = {
GUILD_CREATE: handleGuildCreate,
DELETED_ENTITY_IDS: handleDeletedEntityIds
};
_initialize() {
Dispatcher.subscribe("CONNECTION_OPEN", handleConnectionOpen);
}
_terminate() {
Dispatcher.unsubscribe("CONNECTION_OPEN", handleConnectionOpen);
}
}
c11583_12 = EntityVersionsManager;
const r45 = new EntityVersionsManager();
export default r45;
@@ -0,0 +1,2 @@
// Metro module 13607 (f13608).
export const USE_ALT_GATEWAY_KEY = "use_alt_gateway";
@@ -0,0 +1,24 @@
// Metro module 13606 (f13607).
import { createApexExperiment } from "../experiments/apex/index";
import * as _GatewayAltEndpointCache from "./GatewayAltEndpointCache";
const apexExperiment = createApexExperiment({
name: "2026-07-aws-gateway",
kind: "user",
defaultConfig: {
enableAltGateway: false
},
variations: {
1: {
enableAltGateway: false
},
2: {
enableAltGateway: true
}
}
});
export const USE_ALT_GATEWAY_KEY = _GatewayAltEndpointCache.USE_ALT_GATEWAY_KEY;
export function useShouldUseAltGateway(a0) {
return apexExperiment.useConfig({
location: a0
}).enableAltGateway;
}
+4
View File
@@ -0,0 +1,4 @@
// Metro module 12728 (f12729).
export function getClientCapabilities(a0) {
return a0.useChannelObfuscation ? 1767423 : 1734655;
}
@@ -0,0 +1,272 @@
// Metro module 12708 (f12709).
import { NativeModules } from "react-native";
import { createZstdContextWeb, supportsZstd } from "./GatewayZstdUtils.native";
import * as _Module12711 from "../../_bundle/Module12711";
import Logger from "../debug/Logger";
import * as _PlatformUtils from "../../utils/PlatformUtils";
import * as _Module12710 from "../../_bundle/Module12710";
import { ProcessArgs } from "../../utils/ProcessArgs";
let c8757_6, c8757_7, c8757_8, c8757_9;
let c8757_4 = [];
class BaseGatewayCompressionHandler {
_onDataReady = null;
constructor(a0) {
this._gatewayEncoding = a0;
}
static canUse() {
return false;
}
bindWebSocket() {}
feed() {}
dataReady(a0) {
this._onDataReady = a0;
}
}
const r33 = class extends BaseGatewayCompressionHandler {
_decoder = null;
constructor(a0) {
super(a0);
if (this._gatewayEncoding.wantsString()) {
this._decoder = new TextDecoder("utf-8");
} else {
this._decoder = null;
}
this._stream = createZstdContextWeb();
}
static canUse() {
return false;
}
getAlgorithm() {
return "zstd-stream";
}
usesLegacyCompression() {
return false;
}
feed(a0) {
if (this._stream == null) {
throw new Error("Trying to decompress with zstd but did not initialize with it");
}
if (a0 instanceof ArrayBuffer) {
const r17 = this._stream.decompress(a0);
const r19 = this._decoder != null ? this._decoder.decode(r17) : r17;
if (this._onDataReady != null) {
this._onDataReady(r19);
}
return void 0;
}
throw new Error("Expected array buffer, but got " + typeof a0);
}
close() {}
};
c8757_6 = r33;
c8757_4.push(c8757_6);
const r42 = class extends BaseGatewayCompressionHandler {
_pako = _Module12711;
_usesZstd = false;
_zstdDecoder = null;
_zstdStream = null;
_inflate = new this._pako.Inflate({
chunkSize: 65536,
to: this._gatewayEncoding.wantsString() ? "string" : ""
});
constructor(a0) {
super(a0);
this._inflate.onEnd = this.handleFlushEnd.bind(this);
}
static canUse() {
return false;
}
getAlgorithm() {
return "zlib-stream";
}
usesLegacyCompression() {
return false;
}
feed(a0) {
if (this._inflate == null) {
throw new Error("Trying to feed to closed compression adapter");
}
if (this._onDataReady === null) {
throw new Error("Cannot feed unless a data ready callback is registered.");
}
if (a0 instanceof ArrayBuffer) {
const dataView = new DataView(a0);
this._inflate.push(a0, !!(dataView.byteLength >= 4 && dataView.getUint32(dataView.byteLength - 4, false) === 65535) && this._pako.Z_SYNC_FLUSH);
return void 0;
}
throw new Error("Expected array buffer, but got " + typeof a0);
}
close() {
if (this._inflate != null) {
this._inflate.onEnd = null;
this._inflate.chunks = [];
}
this._inflate = null;
}
handleFlushEnd(a0) {
let r34;
const _pako = this._pako;
const _inflate = this._inflate;
if (_inflate != null) {
if (a0 !== _pako.Z_OK) {
throw new Error(`zlib error, ${a0}, ${_inflate.strm.msg}`);
}
const chunks = _inflate.chunks;
const length = chunks.length;
if (this._gatewayEncoding.wantsString()) {
r34 = length > 1 ? chunks.join("") : chunks[0];
} else if (length > 1) {
const r35 = 0 < length;
let r0 = 0;
let r36 = 0;
let r14 = 0;
if (r35) {
do {
r36 = r36 + chunks[r0].length;
r0 = r0 + 1;
r14 = r36;
} while (r0 < length);
}
const uint8Array = new Uint8Array(r14);
const r45 = 0 < length;
let r46 = 0;
let r47 = 0;
r34 = uint8Array;
if (r45) {
do {
const r48 = chunks[r46];
uint8Array.set(r48, r47);
r47 = r47 + r48.length;
r46 = r46 + 1;
r34 = uint8Array;
} while (r46 < length);
}
} else {
r34 = chunks[0];
}
chunks.length = 0;
if (this._onDataReady != null) {
this._onDataReady(r34);
}
} else {
new Logger("GatewayCompressionHandler").error("flush end happened on closed compression adapter");
}
}
};
c8757_7 = r42;
c8757_4.push(c8757_7);
const r53 = class extends BaseGatewayCompressionHandler {
_pako = _Module12711;
static canUse() {
return false;
}
getAlgorithm() {
return null;
}
usesLegacyCompression() {
return true;
}
feed(a0) {
const _pako = this._pako;
const r12 = a0 instanceof ArrayBuffer && this._gatewayEncoding.wantsString() ? _pako.inflate(a0, {
to: "string"
}) : a0;
if (this._onDataReady == null) {
throw new Error("Cannot feed unless a data ready callback is registered.");
}
this._onDataReady(r12);
}
close() {}
};
c8757_8 = r53;
c8757_4.push(c8757_8);
const r63 = class extends BaseGatewayCompressionHandler {
_socketId = null;
constructor(a0) {
super(a0);
}
static canUse() {
return _PlatformUtils.isAndroid() ? _Module12710.default != null : NativeModules.DCDCompressionManager != null;
}
bindWebSocket(a0) {
this.close();
this._socketId = a0._socketId;
const r16 = supportsZstd();
const isAndroid = _PlatformUtils.isAndroid();
if (r16) {
if (isAndroid) {
if (_Module12710.default != null) {
_Module12710.default.enableZstdStreamSupport(this._socketId);
}
} else {
NativeModules.DCDCompressionManager.enableZstdStreamSupport(this._socketId, 0);
}
} else if (isAndroid) {
if (_Module12710.default != null) {
_Module12710.default.enableZlibStreamSupport(this._socketId);
}
} else {
NativeModules.DCDCompressionManager.enableZlibStreamSupport(this._socketId);
}
}
getAlgorithm() {
return supportsZstd() ? "zstd-stream" : "zlib-stream";
}
usesLegacyCompression() {
return false;
}
feed(a0) {
if (this._onDataReady == null) {
throw new Error("Cannot feed unless a data ready callback is registered.");
}
if (a0 !== null) {
this._onDataReady(a0);
}
}
close() {
const _socketId = this._socketId;
this._socketId = null;
if (_socketId !== null) {
if (_PlatformUtils.isAndroid()) {
if (_Module12710.default != null) {
_Module12710.default.disableZlibStreamSupport(_socketId);
}
} else {
NativeModules.DCDCompressionManager.disableZlibStreamSupport(_socketId);
}
}
}
};
c8757_9 = r63;
c8757_4.push(c8757_9);
class NullGatewayCompressionHandler extends BaseGatewayCompressionHandler {
static canUse() {
return true;
}
getAlgorithm() {
return null;
}
usesLegacyCompression() {
return false;
}
feed(a0) {
if (this._onDataReady == null) {
throw new Error("Cannot feed unless a data ready callback is registered.");
}
this._onDataReady(a0);
}
close() {}
}
c8757_4.push(NullGatewayCompressionHandler);
export function getCompressionHandler(a0) {
if (ProcessArgs.isDiscordGatewayPlaintextSet()) {
return new NullGatewayCompressionHandler(a0);
}
for (const item of c8757_4) {
if (!item.canUse()) {
continue;
}
return new item(a0);
}
return new NullGatewayCompressionHandler(a0);
}
+430
View File
@@ -0,0 +1,430 @@
// Metro module 4865 (f4866).
import UserSettingsProtoStore from "../user_settings/UserSettingsProtoStore";
import AuthenticationStore from "../../stores/AuthenticationStore";
import CallStore from "../../stores/CallStore";
import ChannelStore from "../../stores/ChannelStore";
import MediaEngineStore from "../../stores/MediaEngineStore";
import RTCConnectionStore from "../../stores/RTCConnectionStore";
import RTCRegionStore from "../../stores/RTCRegionStore";
import SelectedChannelStore from "../../stores/SelectedChannelStore";
import SelfPresenceStore from "../../stores/SelfPresenceStore";
import StreamRTCConnectionStore from "../../stores/StreamRTCConnectionStore";
import { AppStates, RTCConnectionStates } from "../../Constants";
import { UserSettingsTypes } from "../user_settings/UserSettingsConstants";
import * as _GatewaySocketSingleton from "./GatewaySocketSingleton";
import { localPresenceState, localVoiceState } from "./GatewaySocketSingleton";
import dispatchSocketMessage from "./dispatchSocketMessage";
import Logger from "../debug/Logger";
import { Storage } from "../../_bundle/Module595";
import { muteCustomJoinSound } from "../soundboard/SoundboardActionCreators";
import SelectedChannelActionCreators from "../../actions/SelectedChannelActionCreators";
import { isIOS } from "../../utils/PlatformUtils";
import { setIsPaused } from "./PauseGatewaySocket";
import Module12 from "../../_bundle/Module12";
import { decodeStreamKey } from "../go_live/utils/StreamKeyUtils";
import ConnectionState from "./ConnectionState";
import Module589 from "../../_bundle/Module589";
import Dispatcher from "../../Dispatcher";
let DiscordNative, c2996_19, c2996_20, sessionId, c2996_22, state, channelId, handleMediaEngineChange, handleLocalPresenceChange;
let _handleConnectionOpen = function _handleConnectionOpen() {
const r8 = async (c25303_0) => {
let c25303_2;
let c29444_0, c29444_1, c29444_2;
L37: {
L34: {
c25303_2 = void 0;
c29444_0 = void 0;
c29444_1 = void 0;
c29444_2 = void 0;
c2996_20 = Date.now();
sessionId = c25303_0.sessionId;
localPresenceState.handleConnectionOpen();
c29444_0 = {};
const voiceChannelId = SelectedChannelStore.getVoiceChannelId();
c29444_1 = voiceChannelId;
if (voiceChannelId != null) {
const r17 = Storage.get("discord_watchdog_restart_timestamp");
const r64 = r17 != null && Date.now() - parseInt(r17, 10) < 60000;
Storage.remove("discord_watchdog_restart_timestamp");
const r72 = window;
const r73 = r72 == null;
let r74 = void 0;
if (!r73) {
const performance2 = r72.performance;
const r84 = performance2 == null;
r74 = void 0;
if (!r84) {
const getEntriesByType = performance2.getEntriesByType;
const r86 = getEntriesByType == null;
r74 = void 0;
if (!r86) {
const r88 = getEntriesByType.call(performance2, "navigation");
r74 = r88 == null ? void 0 : r88[0]?.type;
}
}
}
if (r74 !== "reload" && !r64) {
const r101 = DiscordNative == null;
let r102 = void 0;
if (!r101) {
const processUtils = DiscordNative.processUtils;
const r105 = processUtils == null;
r102 = void 0;
if (!r105) {
const getLastCrash = processUtils.getLastCrash;
r102 = getLastCrash == null ? void 0 : getLastCrash.call(processUtils);
}
}
const rendererCrashReason = (await r102)?.rendererCrashReason;
L33: {
if (rendererCrashReason == null) {
if (c2996_22) {
RTCConnectionStore.setLastSessionVoiceChannelId(c29444_1 != null ? c29444_1 : null);
SelectedChannelActionCreators.selectVoiceChannel(null);
break L33;
}
}
c29444_2 = ChannelStore.getChannel(c29444_1);
if (c29444_2 != null) {
c29444_0 = {
guildId: c29444_2.getGuildId(),
channelId: c29444_1
};
muteCustomJoinSound(c29444_1);
}
}
localVoiceState.update(c29444_0, true);
c2996_22 = false;
channelId = null;
break L34;
}
c29444_2 = ChannelStore.getChannel(c29444_1);
if (c29444_2 != null) {
c29444_0 = {
guildId: c29444_2.getGuildId(),
channelId: c29444_1
};
muteCustomJoinSound(c29444_1);
}
}
localVoiceState.update(c29444_0, true);
c2996_22 = false;
channelId = null;
break L37;
}
return void 0;
}
};
_handleConnectionOpen = r8;
return r8.apply(this, arguments);
};
const handleClipsFlags = function handleClipsFlags() {
localVoiceState.update();
};
handleMediaEngineChange = function handleMediaEngineChange() {
localVoiceState.update();
return false;
};
handleLocalPresenceChange = function handleLocalPresenceChange() {
localPresenceState.update();
return false;
};
DiscordNative = window.DiscordNative;
_GatewaySocketSingleton.socket.dispatcher.getDispatchHandler = dispatchSocketMessage;
c2996_19 = new Logger("ConnectionStore");
c2996_20 = 0;
sessionId = null;
c2996_22 = true;
state = null;
channelId = null;
class GatewayConnectionStore extends Module589.Store {
static displayName = "GatewayConnectionStore";
initialize() {
this.waitFor(AuthenticationStore, CallStore, ChannelStore, MediaEngineStore, RTCConnectionStore, RTCRegionStore, SelectedChannelStore, SelfPresenceStore, StreamRTCConnectionStore, UserSettingsProtoStore);
this.syncWith([MediaEngineStore], handleMediaEngineChange);
this.syncWith([SelfPresenceStore], handleLocalPresenceChange);
}
getSocket() {
return _GatewaySocketSingleton.socket;
}
isTryingToConnect() {
return !_GatewaySocketSingleton.socket.isClosed();
}
isConnected() {
return _GatewaySocketSingleton.socket.isSessionEstablished();
}
isConnectedOrOverlay() {
return _GatewaySocketSingleton.socket.isSessionEstablished() || false;
}
lastTimeConnectedChanged() {
return c2996_20;
}
}
const gatewayConnectionStore = new GatewayConnectionStore(Dispatcher, {
START_SESSION: function handleSessionStart() {
let r13;
if (_GatewaySocketSingleton.socket.isClosed()) {
c2996_19.verbose("Socket is reconnecting because of starting new session");
r13 = _GatewaySocketSingleton.socket.connect();
} else {
c2996_19.verbose("Socket is not reconnecting during a new session because it is not closed");
r13 = false;
}
return r13;
},
LOGIN_SUCCESS: function handleSessionRefresh() {
c2996_19.verbose("session refresh dispatched", {
isEstablished: _GatewaySocketSingleton.socket.isSessionEstablished()
});
let r20 = !!_GatewaySocketSingleton.socket.isSessionEstablished();
if (r20) {
_GatewaySocketSingleton.socket.close();
r20 = _GatewaySocketSingleton.socket.connect();
}
return r20;
},
LOGOUT: function handleLogout(a0) {
if (a0.isSwitchingAccount) {
localPresenceState.handleAccountSwitch();
}
c2996_19.verbose("Closing socket because of logout");
_GatewaySocketSingleton.socket.close();
},
CLEAR_CACHES: function handleClearCaches(a0) {
if (a0.resetSocket) {
_GatewaySocketSingleton.socket.close();
_GatewaySocketSingleton.socket.dispatcher.clear();
_GatewaySocketSingleton.socket.connect();
}
return false;
},
CONNECTION_OPEN: (a0) => {
(function handleConnectionOpen() {
return _handleConnectionOpen.apply(this, arguments);
})(a0);
},
CONNECTION_RESUMED: function handleConnectionResumed() {
channelId = null;
},
CONNECTION_CLOSED: function handleConnectionClosed() {
c2996_19.verbose("connection closed dispatched");
c2996_20 = Date.now();
},
RTC_CONNECTION_STATE: function handleRTCConnectionState(a0) {
if (a0.state !== RTCConnectionStates.DISCONNECTED) {
return false;
}
if (a0.willReconnect) {
if (a0.streamKey != null) {
_GatewaySocketSingleton.socket.streamPing(a0.streamKey);
} else {
_GatewaySocketSingleton.socket.voiceServerPing();
}
}
},
VOICE_CHANNEL_SELECT: function handleVoiceChannelSelect(a0) {
localVoiceState.update({
guildId: a0.guildId,
channelId: a0.channelId
});
channelId = a0.lockVoiceStateForResume ? a0.channelId != null ? a0.channelId : null : null;
if (isIOS() && state === AppStates.BACKGROUND) {
if (a0.channelId == null) {
_GatewaySocketSingleton.socket.close(true);
} else if (_GatewaySocketSingleton.socket.isClosed()) {
setIsPaused(false);
_GatewaySocketSingleton.socket.connect();
}
}
return false;
},
VOICE_STATE_UPDATES: function handleVoiceStateUpdates(a0) {
return a0.voiceStates.reduce((acc, voiceState) => {
if (AuthenticationStore.getId() !== voiceState.userId) {
return acc;
}
if (voiceState.sessionId === sessionId) {
if (channelId != null) {
c2996_19.verbose("Ignoring voice state for own session due to VSU lock on channel:", channelId);
return acc;
}
localVoiceState.setState({
guildId: voiceState.guildId,
channelId: voiceState.channelId
});
} else {
if (voiceState.guildId !== localVoiceState.guildId) {
return acc;
}
localVoiceState.setState({
guildId: null,
channelId: null
});
}
return true;
}, false);
},
GUILD_DELETE: function handleGuildDelete(a0) {
if (a0.guild.id === localVoiceState.guildId) {
localVoiceState.setState({
guildId: null,
channelId: null
});
}
},
CHANNEL_DELETE: function handleChannelDelete(a0) {
if (a0.channel.id === localVoiceState.channelId) {
localVoiceState.setState({
guildId: null,
channelId: null
});
}
},
CALL_DELETE: function handleCallDelete({ channelId: channelId2 }) {
if (channelId2 === localVoiceState.channelId) {
if (channelId === channelId2) {
return false;
}
localVoiceState.setState({
guildId: null,
channelId: null
});
}
},
APP_STATE_UPDATE: function handleFocus(a0) {
if (isIOS()) {
L15: {
if (AuthenticationStore.isAuthenticated()) {
if (state === AppStates.INACTIVE && a0.state === AppStates.BACKGROUND && localVoiceState.channelId == null) {
_GatewaySocketSingleton.socket.close(true);
break L15;
}
if (state === AppStates.BACKGROUND && a0.state === AppStates.ACTIVE && _GatewaySocketSingleton.socket.isClosed()) {
setIsPaused(false);
_GatewaySocketSingleton.socket.connect();
}
}
}
state = a0.state;
} else if (a0.state === AppStates.ACTIVE) {
setIsPaused(false);
if (AuthenticationStore.isAuthenticated()) {
_GatewaySocketSingleton.socket.resetBackoff("App state is active");
}
}
return false;
},
GUILD_MEMBERS_REQUEST: function handleGuildMembersRequest(a0) {
if (_GatewaySocketSingleton.socket.isSessionEstablished()) {
if ("userIds" in a0) {
Module12(a0.userIds).chunk(100).forEach((item) => {
_GatewaySocketSingleton.socket.requestGuildMembers(a0.guildIds, {
userIds: item,
presences: !!a0.presences
});
});
} else {
_GatewaySocketSingleton.socket.requestGuildMembers(a0.guildIds, {
query: a0.query,
limit: a0.limit,
presences: !!a0.presences
});
}
}
return false;
},
GUILD_SEARCH_RECENT_MEMBERS: function handleGuildSearchRecentMembers({ guildId, query, continuationToken }) {
if (_GatewaySocketSingleton.socket.isSessionEstablished()) {
_GatewaySocketSingleton.socket.searchRecentMembers(guildId, {
query,
continuationToken
});
}
},
GUILD_SUBSCRIPTIONS_FLUSH: function handleGuildSubscriptionsFlush({ subscriptions }) {
if (_GatewaySocketSingleton.socket.isSessionEstablished()) {
_GatewaySocketSingleton.socket.updateGuildSubscriptions(subscriptions);
}
return false;
},
CALL_CONNECT: function handleCallConnect({ channelId: channelId2 }) {
if (_GatewaySocketSingleton.socket.isSessionEstablished()) {
_GatewaySocketSingleton.socket.callConnect(channelId2);
}
return false;
},
CALL_CONNECT_MULTIPLE: function handleCallConnectMultiple({ channelIds }) {
if (_GatewaySocketSingleton.socket.isSessionEstablished()) {
channelIds.forEach((channelId) => {
_GatewaySocketSingleton.socket.callConnect(channelId);
});
}
return false;
},
STREAM_CREATE: handleClipsFlags,
STREAM_START: function handleStreamStart({ streamType, guildId, channelId: channelId2 }) {
if (_GatewaySocketSingleton.socket.isSessionEstablished()) {
let r24 = guildId != null ? ChannelStore.getChannel(channelId2)?.rtcRegion : CallStore.getCall(channelId2)?.region;
if (r24 == null) {
r24 = RTCRegionStore.getPreferredRegion();
}
_GatewaySocketSingleton.socket.streamCreate(streamType, guildId, channelId2, r24);
}
return false;
},
STREAM_WATCH: function handleStreamWatch({ streamKey, allowMultiple }) {
if (_GatewaySocketSingleton.socket.isSessionEstablished()) {
if (!allowMultiple) {
let c14477_0 = StreamRTCConnectionStore.getAllActiveStreamKeys().find((item) => decodeStreamKey(item).ownerId === AuthenticationStore.getId());
StreamRTCConnectionStore.getAllActiveStreamKeys().filter((item) => item !== c14477_0).forEach((item) => {
if (_GatewaySocketSingleton.socket.isSessionEstablished()) {
_GatewaySocketSingleton.socket.streamDelete(item);
}
});
}
_GatewaySocketSingleton.socket.streamWatch(streamKey);
}
return false;
},
STREAM_STOP: function handleStreamStop({ streamKey }) {
if (_GatewaySocketSingleton.socket.isSessionEstablished()) {
_GatewaySocketSingleton.socket.streamDelete(streamKey);
}
localVoiceState.update();
return false;
},
STREAM_SET_PAUSED: function handleStreamSetPaused({ streamKey, paused }) {
if (_GatewaySocketSingleton.socket.isSessionEstablished()) {
_GatewaySocketSingleton.socket.streamSetPaused(streamKey, paused);
}
},
PUSH_NOTIFICATION_CLICK: function handlePushNotificationClick() {
_GatewaySocketSingleton.socket.expeditedHeartbeat(5000, "user clicked on notification", true);
return false;
},
REQUEST_FORUM_UNREADS: function handleRequestForumUnreads(a0) {
_GatewaySocketSingleton.socket.requestForumUnreads(a0.guildId, a0.channelId, a0.threads);
},
REQUEST_SOUNDBOARD_SOUNDS: function handleRequestSoundboardSounds(a0) {
_GatewaySocketSingleton.socket.requestSoundboardSounds(a0.guildIds);
},
REMOTE_COMMAND: function handleRemoteCommand({ sessionId: sessionId2, payload }) {
if (_GatewaySocketSingleton.socket.isSessionEstablished()) {
_GatewaySocketSingleton.socket.remoteCommand(sessionId2, payload);
}
return false;
},
RESET_SOCKET: function handleResetSocket(a0) {
if (_GatewaySocketSingleton.socket.connectionState !== ConnectionState.WILL_RECONNECT) {
_GatewaySocketSingleton.socket.resetSocketAndClearCacheOnError(a0.args);
}
},
CLIPS_SETTINGS_UPDATE: handleClipsFlags,
RUNNING_GAMES_CHANGE: handleClipsFlags,
USER_SETTINGS_PROTO_UPDATE: function handleUserSettingsProtoUpdate(a0) {
if (a0.settings.type === UserSettingsTypes.PRELOADED_USER_SETTINGS && a0.settings.proto.clips?.allowVoiceRecording != null) {
localVoiceState.update();
}
}
});
export default gatewayConnectionStore;
+31
View File
@@ -0,0 +1,31 @@
// Metro module 12693 (f12694).
import { getErlpackEncoding } from "./GatewayEncodingErlpackEncoding.native";
import { ProcessArgs } from "../../utils/ProcessArgs";
const erlpackEncoding = getErlpackEncoding();
class JSONEncoding {
constructor() {
return {
__proto__: new.target.prototype
};
}
pack(a0) {
return JSON.stringify(a0);
}
unpack(a0) {
if (typeof a0 !== "string") {
throw new Error(`Expected a string to be passed to JSONEncoding.unpack, got ${a0 != null ? typeof a0 : null}`);
}
return JSON.parse(a0);
}
getName() {
return "json";
}
wantsString() {
return true;
}
}
let r25 = erlpackEncoding !== void 0 ? erlpackEncoding : JSONEncoding;
if (ProcessArgs.isDiscordGatewayPlaintextSet()) {
r25 = JSONEncoding;
}
export default r25;
@@ -0,0 +1,2 @@
// Metro module 12694 (f12695).
export function getErlpackEncoding() {}
+940
View File
@@ -0,0 +1,940 @@
// Metro module 12692 (f12693).
import _slicedToArray from "../../_bundle/_slicedToArray";
import DeveloperOptionsStore from "../../stores/DeveloperOptionsStore";
import { Endpoints, AnalyticEvents } from "../../Constants";
import Logger from "../debug/Logger";
import GatewayEncoding from "./GatewayEncoding";
import createWebSocket_android from "./createWebSocket.android";
import Durations from "../../utils/Durations";
import GatewaySocketOpCodes, { Opcode } from "./GatewaySocketOpCodes";
import Backoff from "../../_bundle/Backoff";
import AltGatewayTracker from "./AltGatewayTracker";
import GatewaySocketDispatcher from "./GatewaySocketDispatcher";
import ConnectionState from "./ConnectionState";
import { getCompressionHandler } from "./GatewayCompressionHandler";
import { getIsPaused } from "./PauseGatewaySocket";
import Module10 from "../../_bundle/Module10";
import TTITracker from "../tti_analytics/TTITracker";
import CrossPlatformNativeUtils_native from "../../utils/CrossPlatformNativeUtils.native";
import { getConnectionPath, logGatewayConnected, createResumeAnalytics } from "./GatewaySocketAnalytics";
import { isIOS } from "../../utils/PlatformUtils";
import { HTTP } from "../../_bundle/sendRequest";
import AnalyticsUtils from "../../utils/AnalyticsUtils";
import Module38 from "../../_bundle/Module38";
import Module589 from "../../_bundle/Module589";
import { isCacheEnabled } from "../cache/isCacheEnabled.native";
import GuildVersions from "../app_database/modules/GuildVersions";
import NonGuildVersions from "../app_database/modules/NonGuildVersions";
import KvCacheVersion from "../app_database/modules/KvCacheVersion";
import { getClientCapabilities } from "./GatewayCapabilities";
import { isChannelMetadataObfuscationEnabled } from "./PrivateChannelHidingExperiment";
import { deflate } from "../../_bundle/Module12711";
import { usesClientMods } from "../../_bundle/Module667";
import MonitoringAgent from "../monitoring/MonitoringAgent";
import { MetricEvents } from "../../_bundle/Module5872";
import SentryUtils_native from "../../utils/SentryUtils.native";
import Dispatcher from "../../Dispatcher";
let byteSize, c8746_9, c8746_10, c8746_13, c8746_14, c8746_15, c8746_16, GATEWAY_ENDPOINT, c8746_19;
let env8746 = {};
const noop = function noop() {};
byteSize = function byteSize(a0) {
return a0 == null ? 0 : typeof a0 === "string" ? a0.length : a0.byteLength;
};
c8746_9 = new Logger("GatewaySocket");
c8746_10 = new GatewayEncoding();
env8746[11] = null;
c8746_13 = 4004;
c8746_14 = 30 * Durations.Millis.SECOND;
c8746_15 = 3 * Durations.Millis.MINUTE;
c8746_16 = 1 * Durations.Millis.MINUTE;
GATEWAY_ENDPOINT = window.GLOBAL_ENV.GATEWAY_ENDPOINT;
class GatewaySocket extends GatewaySocketOpCodes {
dispatchExceptionBackoff = new Backoff(1000, c8746_16);
dispatchSuccessTimer = 0;
didForceClearGuildHashes = false;
identifyUncompressedByteSize = 0;
identifyCompressedByteSize = 0;
analytics = {};
identifyCount = 0;
resumeUrl = null;
iosGoingAwayEventCount = 0;
altGateway = new AltGatewayTracker();
failedConnectAttempts = 0;
receivedHelloThisAttempt = false;
heartbeatQOSState = {
currentPayload: null,
upcomingState: null
};
send = (a0, a1, a2) => {
if (DeveloperOptionsStore.isLoggingGatewayEvents) {
c8746_9.verboseDangerously("~>", a0, Opcode[a0], a1);
}
const r24 = c8746_10.pack({
op: a0,
d: a1
});
if (a2 && !this.isSessionEstablished()) {
c8746_9.warn(`Attempted to send while not being in a connected state opcode: ${a0}`);
} else {
try {
if (this.webSocket != null) {
this.webSocket.send(r24);
}
} catch ($e) {}
}
};
dispatcher = new GatewaySocketDispatcher(this);
gatewayBackoff = new Backoff(1000, 60000);
connectionState_ = ConnectionState.CLOSED;
webSocket = null;
seq = 0;
sessionId = null;
token = null;
initialHeartbeatTimeout = null;
expeditedHeartbeatTimeout = null;
lastHeartbeatTime = null;
lastHeartbeatAckTime = null;
helloTimeout = null;
heartbeatInterval = null;
heartbeater = null;
heartbeatAck = true;
connectionStartTime = 0;
firstConnectAttemptStartTime = 0;
identifyStartTime = 0;
nextReconnectIsImmediate = false;
compressionHandler = getCompressionHandler(c8746_10);
hasConnectedOnce = false;
isFastConnect = false;
constructor() {
super();
this.identifyCount = 0;
this.iosGoingAwayEventCount = 0;
this.failedConnectAttempts = 0;
this.receivedHelloThisAttempt = false;
}
get connectionState() {
return this.connectionState_;
}
set connectionState(a0) {
c8746_9.verbose(`Setting connection state to ${a0}`);
this.connectionState_ = a0;
}
addAnalytics(a0) {
this.analytics = {
...this.analytics,
...a0
};
}
setResumeUrl(a0) {
const resumeUrl = a0 != null && a0.endsWith("/") ? a0.substring(0, a0.length - 1) : a0;
if (resumeUrl !== null) {
c8746_9.verbose(`Updating resume url to ${resumeUrl}`);
}
this.resumeUrl = resumeUrl;
}
handleActiveStateChange(a0) {
const active = this.heartbeatQOSState.currentPayload?.active;
let r7 = !active;
if (this.heartbeatQOSState.currentPayload == null) {
this.heartbeatQOSState.currentPayload = a0;
}
const currentPayload = this.heartbeatQOSState.currentPayload;
if (a0.active) {
currentPayload.active = true;
currentPayload.reasons = [...new Set([...currentPayload.reasons, ...a0.reasons])].sort();
if (!active) {
r7 = this.isSessionEstablished();
}
if (r7) {
this._sendHeartbeat();
}
}
this.heartbeatQOSState.upcomingState = a0;
}
handleUpdateTimeSpentSessionId(a0, a1, a2) {
if (this.connectionState_ === ConnectionState.SESSION_ESTABLISHED) {
this.send(Opcode.UPDATE_TIME_SPENT_SESSION_ID, {
initialization_timestamp: a0,
session_id: a1,
client_launch_id: a2
});
this._sendHeartbeat();
}
}
_connect() {
let env19967 = {
$parent: env8746
};
env19967[1] = this;
if (this.willReconnect()) {
if (getIsPaused()) {
c8746_9.info("Skipping _connect because socket is paused");
} else {
this.connectionState = ConnectionState.CONNECTING;
this.nextReconnectIsImmediate = false;
const algorithm = this.compressionHandler.getAlgorithm();
const name = c8746_10.getName();
const r12 = this._getGatewayUrl();
const API_VERSION = window.GLOBAL_ENV.API_VERSION;
this.receivedHelloThisAttempt = false;
Module10.mark("🌐", "Socket._connect");
let r24 = algorithm;
if (r24 == null) {
r24 = "none";
}
c8746_9.info(`[CONNECT] ${r12}, encoding: ${name}, version: ${API_VERSION}, compression: ${r24}`);
if (this.webSocket !== null) {
c8746_9.error("_connect called with already existing websocket");
this._cleanup((a0) => a0.close(4000));
}
this.connectionStartTime = Date.now();
if (this.firstConnectAttemptStartTime === 0) {
this.firstConnectAttemptStartTime = this.connectionStartTime;
}
this.helloTimeout = setTimeout(() => {
const r5 = Date.now();
const r9 = env19967[1];
r9._handleClose(false, 0, `The connection timed out after ${r5 - r9.connectionStartTime} ms - did not receive OP_HELLO in time.`);
r9.setResumeUrl(null);
}, c8746_14);
const uRL = new URL(r12);
env19967[0] = uRL;
uRL.searchParams.append("encoding", name);
uRL.searchParams.append("v", API_VERSION.toString());
if (algorithm != null) {
uRL.searchParams.append("compress", algorithm);
}
let c19968_3, c19968_4;
let onOpen2, identify;
const r22 = uRL.toString();
const compressionHandler2 = this.compressionHandler;
const r104 = this._handleClose.bind(this);
const compressionHandler = compressionHandler2;
let c19968_2 = (a0, a1) => {
const r17 = Date.now();
const r26 = c8746_10.unpack(a0);
const { op, s: seq, t: r9, d: r7 } = r26;
if (op !== Opcode.DISPATCH) {
Module10.mark("🌐", `GatewaySocket.onMessage ${op} ${Opcode[op]}`);
}
if (DeveloperOptionsStore.isLoggingGatewayEvents) {
const r43 = [op];
if (op === Opcode.DISPATCH) {
r43.push(r9);
}
r43.push(r7);
c8746_9.verboseDangerously.apply(c8746_9, ["<~", ...r43]);
}
const unpack_duration_ms = Date.now() - r17;
const r3 = r9 === "READY";
if (r3) {
TTITracker.parseReady.set(r17, unpack_duration_ms);
} else if (r9 === "READY_SUPPLEMENTAL") {
TTITracker.parseReadySupplemental.set(r17, unpack_duration_ms);
} else if (unpack_duration_ms > 10) {
Module10.mark("🌐", "Parse " + r9, unpack_duration_ms);
}
if (seq != null) {
env19967[1].seq = seq;
}
if (Opcode.HELLO === op) {
const r145 = env19967[1];
r145._clearHelloTimeout();
r145._handleHello(r7);
} else if (Opcode.RECONNECT === op) {
env19967[1]._handleReconnect();
} else if (Opcode.INVALID_SESSION === op) {
env19967[1]._handleInvalidSession(r7);
} else if (Opcode.HEARTBEAT === op) {
env19967[1]._handleHeartbeatReceive();
} else if (Opcode.HEARTBEAT_ACK === op) {
env19967[1]._handleHeartbeatAck(r7);
} else if (Opcode.DISPATCH === op) {
const r119 = env19967[1];
r119._handleDispatch(r7, r9, r3 ? {
compressed_byte_size: a1,
uncompressed_byte_size: a0 == null ? 0 : typeof a0 === "string" ? a0.length : a0.byteLength,
compression_algorithm: r119.compressionHandler.getAlgorithm(),
packing_algorithm: c8746_10.getName(),
unpack_duration_ms
} : null);
} else {
c8746_9.info(`Unhandled op ${op}`);
}
env19967[1]._sendHeartbeatIfDue();
};
c19968_4 = void 0;
c19968_3 = 0;
compressionHandler.dataReady((a0) => {
try {
c19968_2(a0, c19968_3);
} catch (r7) {
c19968_3 = 0;
throw r7;
}
c19968_3 = 0;
});
c19968_4 = false;
onOpen2 = (a0) => {};
identify = void 0;
c8746_9.enableNativeLogger(true);
const _ws = window._ws;
identify = false;
window._ws = null;
const r117 = _ws != null;
let r118 = null;
let isFastConnect = false;
let r120 = false;
let webSocket = void 0;
if (r117) {
const ws = _ws.ws;
const userId = _ws.state.userId;
const r124 = userId != null && env8746[11] != null && userId !== env8746[11];
if (_ws.state.gateway !== r22) {
c8746_9.verbose(`[FAST CONNECT] gatewayURL mismatch: ${_ws.state.gateway} !== ${r22}`);
ws.close(1000);
r118 = null;
isFastConnect = false;
r120 = false;
webSocket = null;
} else if (r124) {
c8746_9.log(`[FAST CONNECT] refusing to adopt socket: identified user ${userId} does not match switch target ${env8746[11]}`);
ws.close(1000);
r118 = null;
isFastConnect = false;
r120 = false;
webSocket = null;
} else {
const r129 = {
..._ws.state
};
if (r129.messages != null) {
r129.messages = r129.messages.map((message) => message.data != null ? typeof message.data === "string" ? {
...message,
data: message.data.substring(0, 100)
} : message : message);
}
c8746_9.log("[FAST CONNECT] successfully took over websocket, state:", {
...r129,
messages: r129.messages?.length
});
r120 = _ws.state.open;
const identify2 = _ws.state.identify;
identify = identify2;
r118 = _ws.state.messages;
_ws.state.clientState;
isFastConnect = identify2;
webSocket = ws;
}
}
if (webSocket == null) {
const webSocket_android = createWebSocket_android(r22);
webSocket_android.binaryType = "arraybuffer";
webSocket = webSocket_android;
}
this.webSocket = webSocket;
this.compressionHandler.bindWebSocket(webSocket);
if (r120) {
Module10.mark("🌐", `GatewaySocket.onOpen ${isFastConnect}`);
const r192 = Date.now() - this.connectionStartTime;
c8746_9.info(`[CONNECTED] ${uRL.toString()} in ${r192} ms`);
this.isFastConnect = isFastConnect;
if (isFastConnect) {
this._doFastConnectIdentify();
} else {
this._doResumeOrIdentify();
}
}
const onmessage = (a0) => {
const data = a0.data;
if (a0.raw_length != null) {
c19968_3 = c19968_3 + a0.raw_length;
} else {
c19968_3 = c19968_3 + byteSize(data);
}
try {
compressionHandler.feed(data);
} catch (r18) {
if (!c19968_4) {
c19968_4 = true;
this(false, 0, "A decompression error occurred");
}
throw r18;
}
};
if (r118 != null) {
r118.forEach(onmessage);
}
const onError = () => {
const r5 = env19967[1];
r5.setResumeUrl(null);
CrossPlatformNativeUtils_native.flushDNSCache();
r5._handleClose(false, 0, "An error with the websocket occurred");
};
const onClose = (a0) => env19967[1]._handleClose(a0.wasClean, a0.code, a0.reason);
webSocket.onopen = () => {
Module10.mark("🌐", `GatewaySocket.onOpen ${identify}`);
const r26 = Date.now();
const r27 = env19967[1];
const r12 = r26 - r27.connectionStartTime;
c8746_9.info(`[CONNECTED] ${env19967[0].toString()} in ${r12} ms`);
r27.isFastConnect = identify;
if (identify) {
r27._doFastConnectIdentify();
} else {
r27._doResumeOrIdentify();
}
};
webSocket.onmessage = onmessage;
webSocket.onclose = onClose;
webSocket.onerror = onError;
}
} else {
c8746_9.verbose("Skipping _connect because willReconnect is false");
}
}
_handleHello(a0) {
const heartbeat_interval = a0.heartbeat_interval;
this.heartbeatInterval = heartbeat_interval;
const now = Date.now();
const r18 = now - this.connectionStartTime;
c8746_9.verbose(`[HELLO] via ${getConnectionPath(a0)}, heartbeat interval: ${heartbeat_interval}, took ${r18} ms`);
logGatewayConnected({
socket: this,
altGateway: this.altGateway,
gatewayUrl: this._getGatewayUrl(),
now
});
this.receivedHelloThisAttempt = true;
this.failedConnectAttempts = 0;
this.firstConnectAttemptStartTime = 0;
this._startHeartbeater();
}
_handleReconnect() {
c8746_9.verbose("[RECONNECT] gateway requested I reconnect.");
this._cleanup((a0) => a0.close(4000));
this.connectionState = ConnectionState.WILL_RECONNECT;
this._connect();
}
_handleInvalidSession(a0) {
c8746_9.info("[INVALID_SESSION]" + (a0 ? " can resume)" : ""));
if (a0) {
this._doResumeOrIdentify();
} else {
this._doIdentify();
}
}
_handleDispatch(a0, a1, a2) {
const r15 = Date.now() - this.connectionStartTime;
if (a1 === "READY") {
const session_id = a0.session_id;
this.sessionId = session_id;
const connectionPath = getConnectionPath(a0);
Module10.setServerTrace(connectionPath);
c8746_9.info(`[READY] took ${r15}ms, as ${session_id}`);
c8746_9.verbose(`${connectionPath}`);
this.connectionState = ConnectionState.SESSION_ESTABLISHED;
this.gatewayBackoff.succeed();
this.iosGoingAwayEventCount = 0;
this.altGateway.recordSuccess();
this.setResumeUrl(a0.resume_gateway_url);
} else if (a1 === "READY_SUPPLEMENTAL") {
c8746_9.info(`[READY_SUPPLEMENTAL] took ${r15}ms`);
this.connectionState = ConnectionState.SESSION_ESTABLISHED;
this.gatewayBackoff.succeed();
this.iosGoingAwayEventCount = 0;
this.altGateway.recordSuccess();
} else if (a1 === "RESUMED") {
c8746_9.verbose(getConnectionPath(a0));
this.connectionState = ConnectionState.SESSION_ESTABLISHED;
this.gatewayBackoff.succeed();
this.iosGoingAwayEventCount = 0;
this.altGateway.recordSuccess();
}
this.dispatcher.receiveDispatch(a0, a1, a2);
}
handleResumeDispatched() {
c8746_9.info(`[RESUMED] took ${Date.now() - this.connectionStartTime}ms, replayed ${this.dispatcher.resumeAnalytics.numEvents} events, new seq: ${this.seq}`);
}
handleReadyDispatched() {
this.didForceClearGuildHashes = false;
this.hasConnectedOnce = true;
}
_getGatewayUrl() {
let resumeUrl;
if (this.resumeUrl != null) {
resumeUrl = this.resumeUrl;
} else {
resumeUrl = this.altGateway.getAltGatewayUrl();
if (resumeUrl == null) {
resumeUrl = GATEWAY_ENDPOINT;
}
}
return resumeUrl;
}
_maybeFallBackFromAltGateway() {
if (this.altGateway.shouldUseAltGateway()) {
this.altGateway.recordFailure();
if (!this.altGateway.shouldUseAltGateway()) {
this.gatewayBackoff.succeed();
this.setResumeUrl(null);
c8746_9.warn("[ALT GATEWAY] 3 consecutive failures, falling back to default URL for this session.");
}
}
}
_handleHeartbeatReceive() {
this._sendHeartbeat();
if (this.heartbeater != null && this.heartbeatInterval != null) {
clearInterval(this.heartbeater);
this.heartbeater = setInterval(this._doHeartbeatInterval.bind(this), this.heartbeatInterval);
}
}
_handleHeartbeatAck() {
this.lastHeartbeatAckTime = Date.now();
this.heartbeatAck = true;
if (this.expeditedHeartbeatTimeout !== null) {
clearTimeout(this.expeditedHeartbeatTimeout);
this.expeditedHeartbeatTimeout = null;
c8746_9.verbose("Expedited heartbeat succeeded");
}
}
_handleHeartbeatTimeout() {
this._cleanup((a0) => a0.close(4000));
this.connectionState = ConnectionState.WILL_RECONNECT;
this._maybeFallBackFromAltGateway();
c8746_9.warn(`[ACK TIMEOUT] reconnecting in ${(this.gatewayBackoff.fail(() => this._connect()) / 1000).toFixed(2)} seconds.`);
}
_handleClose(a0, a1, a2) {
const r6 = a0 ? a0 : false;
this._cleanup();
this.emit("close", {
code: a1,
reason: a2
});
if (a1 === c8746_13) {
this.connectionState = ConnectionState.CLOSED;
c8746_9.warn("[WS CLOSED] because of authentication failure, marking as closed.");
return this._reset(r6, a1, a2);
}
this._tryDetectInvalidIOSToken(a1, a2, r6);
this.connectionState = ConnectionState.WILL_RECONNECT;
if (!this.receivedHelloThisAttempt) {
this.failedConnectAttempts = this.failedConnectAttempts + 1;
}
this._maybeFallBackFromAltGateway();
if (this.nextReconnectIsImmediate) {
c8746_9.info(`[WS CLOSED] (${r6.toString()}, ${a1}, ${a2}) retrying immediately.`);
this._connect();
} else {
const r46 = this.gatewayBackoff.fail(() => this._connect());
c8746_9.info(`[WS CLOSED] (${r6.toString()}, ${a1}, ${a2}) retrying in ${(r46 / 1000).toFixed(2)} seconds.`);
if (this.gatewayBackoff.fails > 4) {
this._reset(r6, a1, a2);
}
}
}
_tryDetectInvalidIOSToken(a0, a1, c19972_0) {
if (isIOS() && this.token != null && a0 === 1001 && a1 === "Stream end encountered") {
this.iosGoingAwayEventCount = this.iosGoingAwayEventCount + 1;
if (this.iosGoingAwayEventCount === 3) {
HTTP.get({
url: Endpoints.ME,
headers: {
authorization: this.token
},
rejectWithError: false
}).then((result) => {
AnalyticsUtils.track(AnalyticEvents.IOS_INVALID_TOKEN_WORKAROUND_TRIGGERED, {
api_status_code: result.status
});
}, ({ status }) => {
if (status === 401) {
this.connectionState = ConnectionState.CLOSED;
c8746_9.warn("[WS CLOSED] because of manual authentication failure, marking as closed.");
this._reset(c19972_0, c8746_13, "invalid token manually detected");
}
AnalyticsUtils.track(AnalyticEvents.IOS_INVALID_TOKEN_WORKAROUND_TRIGGERED, {
api_status_code: status
});
});
}
}
}
_reset(a0, a1, a2) {
this.sessionId = null;
this.seq = 0;
c8746_9.warn(`[RESET] (${a0.toString()}, ${a1}, ${a2})`);
this.emit("disconnect", {
wasClean: a0,
code: a1,
reason: a2
});
}
_sendHeartbeatIfDue() {
if (this.heartbeatInterval != null && this.heartbeater != null) {
const lastHeartbeatTime = this.lastHeartbeatTime;
if (lastHeartbeatTime != null && Date.now() - lastHeartbeatTime > this.heartbeatInterval + 5000) {
this._sendHeartbeat();
}
}
}
_doHeartbeatInterval() {
if (this.heartbeatAck) {
this.heartbeatAck = false;
this._sendHeartbeat();
} else if (this.expeditedHeartbeatTimeout === null) {
this._handleHeartbeatTimeout();
}
}
_startHeartbeater() {
const heartbeatInterval = this.heartbeatInterval;
Module38(heartbeatInterval != null, "GatewaySocket: Heartbeat interval should never null here.");
if (this.initialHeartbeatTimeout !== null) {
clearTimeout(this.initialHeartbeatTimeout);
}
if (this.heartbeater !== null) {
clearInterval(this.heartbeater);
this.heartbeater = null;
}
this.initialHeartbeatTimeout = setTimeout(() => {
this.initialHeartbeatTimeout = null;
this.heartbeatAck = true;
this.heartbeater = setInterval(this._doHeartbeatInterval.bind(this), heartbeatInterval);
this._doHeartbeatInterval();
}, Math.floor(Math.random() * heartbeatInterval));
}
_stopHeartbeater() {
if (this.heartbeater !== null) {
clearInterval(this.heartbeater);
this.heartbeater = null;
}
if (this.initialHeartbeatTimeout !== null) {
clearTimeout(this.initialHeartbeatTimeout);
this.initialHeartbeatTimeout = null;
}
if (this.expeditedHeartbeatTimeout !== null) {
clearTimeout(this.expeditedHeartbeatTimeout);
this.expeditedHeartbeatTimeout = null;
}
}
_clearHelloTimeout() {
if (this.helloTimeout != null) {
clearTimeout(this.helloTimeout);
this.helloTimeout = null;
}
}
_cleanup(a0) {
Module589.Emitter.resume();
this._stopHeartbeater();
this._clearHelloTimeout();
const webSocket = this.webSocket;
this.webSocket = null;
if (webSocket != null) {
webSocket.onopen = noop;
webSocket.onmessage = noop;
webSocket.onerror = noop;
webSocket.onclose = noop;
if (a0 != null) {
a0(webSocket);
}
}
this.gatewayBackoff.cancel();
this.compressionHandler.close();
this.compressionHandler = getCompressionHandler(c8746_10);
}
_doResume() {
this.connectionState = ConnectionState.RESUMING;
this.dispatcher.resumeAnalytics = createResumeAnalytics(Date.now() - this.connectionStartTime);
let sessionId = this.sessionId;
if (sessionId == null) {
sessionId = "";
}
c8746_9.info(`[RESUME] resuming session ${sessionId}, seq: ${this.seq}`);
this.send(Opcode.RESUME, {
token: this.token,
session_id: this.sessionId,
seq: this.seq
}, false);
}
async _doIdentify() {
const _this = this;
let c27352_1;
let c30572_0, c30572_1, c30572_2, c30572_3, c30572_4, c30572_5, c30572_6, c30572_7, c30572_8, c30572_9, c30572_10, c30572_11, c30572_12;
L31: {
c27352_1 = void 0;
c30572_0 = void 0;
c30572_1 = void 0;
c30572_2 = void 0;
c30572_3 = void 0;
c30572_4 = void 0;
c30572_5 = void 0;
c30572_6 = void 0;
c30572_7 = void 0;
c30572_8 = void 0;
c30572_9 = void 0;
c30572_10 = void 0;
c30572_11 = void 0;
c30572_12 = void 0;
_this.seq = 0;
_this.sessionId = null;
const r35 = _this.handleIdentify();
c30572_0 = r35;
if (r35 !== null) {
_this.connectionState = ConnectionState.IDENTIFYING;
const identifyStartTime = Date.now();
c30572_1 = identifyStartTime;
_this.identifyStartTime = identifyStartTime;
c30572_2 = await Promise.all([isCacheEnabled() ? GuildVersions.getCommittedVersions() : {}, isCacheEnabled() ? NonGuildVersions.getCommittedVersions() : {}, !!isCacheEnabled() && KvCacheVersion.canUseGuildVersions()]);
c30572_3 = (0, _slicedToArray)(c30572_2, 3);
c30572_4 = c30572_3[0];
c30572_5 = c30572_3[1];
c30572_6 = c30572_3[2] ? {
guild_versions: c30572_4,
highest_last_message_id: c30572_5.highest_last_message_id,
read_state_version: c30572_5.read_state_version,
user_guild_settings_version: c30572_5.user_guild_settings_version,
user_settings_version: c30572_5.user_settings_version,
private_channels_version: c30572_5.private_channels_version,
api_code_version: c30572_5.api_code_version,
initial_guild_id: c30572_5.initial_guild_id
} : {
guild_versions: {}
};
if (_this.connectionState === ConnectionState.IDENTIFYING && _this.identifyStartTime === c30572_1) {
c30572_7 = c30572_0.token;
c30572_8 = c30572_0.properties;
c30572_9 = c30572_8 === void 0 ? {} : c30572_8;
c30572_10 = c30572_0.presence;
_this.token = c30572_7;
c8746_9.verbose("[IDENTIFY]");
c30572_11 = {
token: c30572_7,
capabilities: getClientCapabilities({
useChannelObfuscation: isChannelMetadataObfuscationEnabled("GatewaySocket")
}),
properties: c30572_9,
presence: c30572_10,
compress: _this.compressionHandler.usesLegacyCompression(),
client_state: c30572_6
};
c30572_12 = JSON.stringify(c30572_11);
_this.identifyUncompressedByteSize = c30572_12.length;
_this.identifyCompressedByteSize = deflate(c30572_12).length;
_this.identifyCount = _this.identifyCount + 1;
_this.send(Opcode.IDENTIFY, c30572_11, false);
AnalyticsUtils.track(AnalyticEvents.SESSION_START_CLIENT, {});
break L31;
}
c8746_9.warn("Skipping identify because connectionState or identifyStartTime has changed");
break L31;
}
_this._handleClose(true, c8746_13, "No connection info provided");
return void 0;
}
}
_doFastConnectIdentify() {
this.seq = 0;
this.sessionId = null;
const r8 = this.handleIdentify();
if (r8 !== null) {
this.token = r8.token;
this.connectionState = ConnectionState.IDENTIFYING;
this.identifyStartTime = Date.now();
this.identifyCount = this.identifyCount + 1;
c8746_9.verbose("[IDENTIFY, fast-connect]");
this._updateLastHeartbeatAckTime();
} else {
this._handleClose(true, c8746_13, "No connection info provided");
}
}
_doResumeOrIdentify() {
L5: {
L3: {
const r4 = Date.now();
if (this.sessionId !== null) {
if (this.lastHeartbeatAckTime != null && !(r4 - this.lastHeartbeatAckTime <= c8746_15)) {
break L3;
}
this._doResume();
break L5;
}
}
this._doIdentify();
}
this._updateLastHeartbeatAckTime();
}
_updateLastHeartbeatAckTime() {
this.lastHeartbeatAckTime = Date.now();
}
_consumeQOSPayload() {
const currentPayload = this.heartbeatQOSState.currentPayload;
const heartbeatQOSState = this.heartbeatQOSState;
let upcomingState = this.heartbeatQOSState.upcomingState;
if (upcomingState == null) {
upcomingState = this.heartbeatQOSState.currentPayload;
}
heartbeatQOSState.currentPayload = upcomingState;
this.heartbeatQOSState.upcomingState = null;
return currentPayload;
}
_sendHeartbeat() {
this.send(Opcode.QOS_HEARTBEAT, {
seq: this.seq,
qos: this._consumeQOSPayload()
}, false);
this.lastHeartbeatTime = Date.now();
}
getLogger() {
return c8746_9;
}
willReconnect() {
return this.connectionState === ConnectionState.WILL_RECONNECT;
}
isClosed() {
return this.connectionState === ConnectionState.CLOSED;
}
isSessionEstablished() {
return this.connectionState === ConnectionState.SESSION_ESTABLISHED || this.connectionState === ConnectionState.RESUMING;
}
isConnected() {
return this.connectionState === ConnectionState.IDENTIFYING || this.connectionState === ConnectionState.RESUMING || this.connectionState === ConnectionState.SESSION_ESTABLISHED;
}
connect() {
let r1;
if (this.isClosed()) {
this.altGateway.reset();
c8746_9.verbose(".connect() called, new state is WILL_RECONNECT");
this.connectionState = ConnectionState.WILL_RECONNECT;
this.firstConnectAttemptStartTime = 0;
this._connect();
r1 = true;
} else {
c8746_9.error("Cannot start a new connection, connection state is not closed");
r1 = false;
}
return r1;
}
resetSocketAndClearCacheOnError(a0) {
const { action, error } = a0;
let metricAction = a0.metricAction;
c8746_9.error(`resetSocketAndClearCacheOnError during ${action}: ${error.message}`, error.stack);
const has_client_mods = usesClientMods();
if (metricAction == null) {
metricAction = action;
}
MonitoringAgent.increment({
name: MetricEvents.SOCKET_CRASHED,
tags: [`action:${metricAction}`, `modded_client:${has_client_mods}`]
}, true);
if (a0.sentry !== false) {
SentryUtils_native.captureException(error, {
tags: {
socketCrashedAction: action
}
});
}
AnalyticsUtils.track(AnalyticEvents.GATEWAY_SOCKET_RESET, {
error_message: error.message,
error_stack: error.stack,
has_client_mods,
action
});
this._cleanup((a0) => a0.close());
this._reset(true, 1000, "Resetting socket due to error.");
this.dispatcher.clear();
this.connectionState = ConnectionState.WILL_RECONNECT;
this.dispatchExceptionBackoff.cancel();
if (this.dispatchExceptionBackoff._fails === 0) {
c8746_9.verbose("Triggering fast reconnect");
this.dispatchExceptionBackoff.fail(() => {});
setTimeout(() => this._connect(), 0);
} else {
this.dispatchExceptionBackoff.fail(() => this._connect());
}
this.didForceClearGuildHashes = true;
Dispatcher.dispatch({
type: "CLEAR_CACHES",
reason: `Socket reset during ${action}`
});
Dispatcher.dispatch({
type: "LIBDISCORE_RESET"
});
clearTimeout(this.dispatchSuccessTimer);
this.dispatchSuccessTimer = setTimeout(() => this.dispatchExceptionBackoff.succeed(), 2 * c8746_16);
}
resetSocketOnDispatchError(a0) {
this.resetSocketAndClearCacheOnError({
...a0,
sentry: !(a0.error.message != null && a0.error.message.indexOf("Guild data was missing from store") >= 0)
});
}
close(r3 = false) {
const isClosed2 = this.isClosed();
if (isClosed2) {
c8746_9.verbose("close() called, but socket is already closed.");
if (!r3) {
this.sessionId = null;
this.token = null;
}
return void 0;
}
c8746_9.info(`Closing connection, current state is ${this.connectionState}`);
let c19976_0 = r3 ? 4000 : void 0;
this._cleanup((a0) => a0.close(c19976_0));
this.connectionState = ConnectionState.CLOSED;
if (!r3) {
this.sessionId = null;
this.token = null;
setImmediate(() => {
this._reset(true, 1000, "Disconnect requested by user");
});
}
}
networkStateChange(a0, a1, r6 = true) {
this.expeditedHeartbeat(a0, a1, r6, false);
}
expeditedHeartbeat(a0, r10 = "", r7 = true, r9 = true) {
if (this.isClosed()) {
return void 0;
}
if (this.isConnected()) {
c8746_9.verbose("Performing an expedited heartbeat " + (r10 != null ? r10 !== "" ? "reason: " + r10 : "" : ""));
this.heartbeatAck = false;
this._sendHeartbeat();
if (this.expeditedHeartbeatTimeout !== null) {
clearTimeout(this.expeditedHeartbeatTimeout);
}
this.expeditedHeartbeatTimeout = setTimeout(() => {
this.expeditedHeartbeatTimeout = null;
if (this.heartbeatAck === false) {
this._handleHeartbeatTimeout();
}
}, a0);
} else if (r7) {
this.resetBackoff(r10, r9);
} else {
c8746_9.verbose(`Expedited heartbeat requested, but, connection state is ${this.connectionState} and reconnectImmediately was not requested ${r10 != null ? r10 !== "" ? "reason: " + r10 : "" : ""}`);
}
}
resetBackoff(r6 = "", r4 = true) {
c8746_9.verbose("Connection has reset backoff" + (r6 != null ? r6 !== "" ? " for reason: " + r6 : "" : ""));
this.gatewayBackoff.succeed();
this.iosGoingAwayEventCount = 0;
this.nextReconnectIsImmediate = true;
if (this.willReconnect()) {
this._connect();
} else {
if (r4) {
r4 = this.connectionState !== ConnectionState.SESSION_ESTABLISHED;
}
if (r4) {
this._handleClose(true, 0, r6);
}
}
}
}
c8746_19 = GatewaySocket;
export default GatewaySocket;
export function setAccountSwitchUserId(a0) {
env8746[11] = a0;
}
+359
View File
@@ -0,0 +1,359 @@
// Metro module 12705 (f12706).
import _objectWithoutProperties from "../../_bundle/_objectWithoutProperties";
import UserStore from "../../stores/UserStore";
import { AnalyticEvents, ChannelTypes } from "../../Constants";
import Module10 from "../../_bundle/Module10";
import TTITracker from "../tti_analytics/TTITracker";
import AnalyticsUtils from "../../utils/AnalyticsUtils";
import { HermesBuiltin } from "../../_hermes/prelude";
let _excluded, _excluded2, _excluded3, eachTraceCall;
const prettyPrintTrace_ = function prettyPrintTrace_(calls, a1) {
let length;
if (calls == null) {
return "";
}
const r26 = 0 < calls.length;
let r10 = "";
let r0 = 0;
let r27 = "";
if (r26) {
do {
const r23 = calls[r0];
const r1 = r0 + 1;
r10 = r10 + `
${a1}${r23}: ${calls[r1].micros / 1000}` + prettyPrintTrace_(calls[r1].calls, a1 + "| ");
r0 = r0 + 2;
length = calls.length;
r27 = r10;
} while (r0 < length);
}
return r27;
};
eachTraceCall = function eachTraceCall(calls, a1) {
if (calls != null && calls.length > 0) {
const r6 = 0 < calls.length;
let r0 = 0;
if (r6) {
do {
const r12 = calls[r0];
const r15 = calls[r0 + 1];
a1(r12, r15.micros);
eachTraceCall(r15.calls, a1);
r0 = r0 + 2;
} while (r0 < calls.length);
}
}
};
_excluded = ["guilds", "merged_presences", "merged_members", "read_state", "private_channels", "user_guild_settings", "user_settings", "user_settings_proto", "experiments", "guild_experiments", "relationships", "users"];
_excluded2 = ["features"];
_excluded3 = ["threads", "guild_scheduled_events"];
export function reportDevtoolsEvent() {}
export function logReadyPayloadReceived(a0, a1, a2, a3, a4) {
const r13 = (function getReadyPayloadTraceAnalytics({ _trace }) {
const r8 = {};
let c27353_0 = r8;
try {
const r9 = JSON.parse(_trace);
if (r9[0] != null && r9[0] !== "" && typeof r9[0] === "string" && r9[0].startsWith("gateway-")) {
r8.identify_total_server_duration_ms = typeof r9[1] === "object" ? "micros" in r9[1] ? Math.floor(r9[1].micros / 1000) : 0 : 0;
}
eachTraceCall(r9, (a0, a1) => {
if (a0 === "start_session") {
c27353_0.identify_api_duration_ms = Math.floor(a1 / 1000);
} else if (a0 === "guilds_connect") {
c27353_0.identify_guilds_duration_ms = Math.floor(a1 / 1000);
}
});
} catch ($e) {}
return r8;
})(a1);
if (a3 != null) {
Module10.addDetail("payload_size(kb)", Math.round(a3.uncompressed_byte_size / 1024));
}
let identify_total_server_duration_ms = r13.identify_total_server_duration_ms;
if (identify_total_server_duration_ms == null) {
identify_total_server_duration_ms = 0;
}
Module10.addDetail("server_time(ms)", identify_total_server_duration_ms);
const r38 = {
...a3,
...r13
};
const guilds = a1.guilds;
let num_guild_category_channels = 0;
let num_guild_channels = 0;
guilds.forEach((guild) => {
if (!guild.unavailable) {
const r6 = guild.data_mode === "partial" ? guild.partial_updates.channels : guild.channels;
if (r6 != null && r6.forEach != null) {
r6.forEach((item) => {
num_guild_channels = num_guild_channels + 1;
if (item.type === ChannelTypes.GUILD_CATEGORY) {
num_guild_category_channels = num_guild_category_channels + 1;
}
});
}
}
});
HermesBuiltin.copyDataProperties(r38, {
num_guilds: guilds.length,
num_guild_channels,
num_guild_category_channels
});
HermesBuiltin.copyDataProperties(r38, a4);
r38.duration_ms_since_identify_start = a2 - a0.identifyStartTime;
r38.duration_ms_since_connection_start = a2 - a0.connectionStartTime;
r38.duration_ms_since_emit_start = Date.now() - a2;
r38.is_reconnect = a0.hasConnectedOnce;
r38.is_fast_connect = a0.isFastConnect;
r38.did_force_clear_guild_hashes = a0.didForceClearGuildHashes;
r38.identify_uncompressed_byte_size = a0.identifyUncompressedByteSize;
r38.identify_compressed_byte_size = a0.identifyCompressedByteSize;
let hadCacheAtStartup = a0.analytics.hadCacheAtStartup;
if (hadCacheAtStartup == null) {
hadCacheAtStartup = false;
}
r38.had_cache_at_startup = hadCacheAtStartup;
let usedCacheAtStartup = a0.analytics.usedCacheAtStartup;
if (usedCacheAtStartup == null) {
usedCacheAtStartup = false;
}
r38.used_cache_at_startup = usedCacheAtStartup;
TTITracker.attachReadyPayloadProperties(r38);
AnalyticsUtils.track(AnalyticEvents.READY_PAYLOAD_RECEIVED, r38, {
logEventProperties: true
});
}
export function getConnectionPath(a0) {
let r10;
L5: {
try {
const _trace = a0._trace;
const r9 = (function prettyPrintTrace(a0) {
let length, length2;
const r9 = a0 == null;
let r11 = null;
if (!r9) {
const r21 = JSON.parse(a0);
const r36 = r21 == null;
let r37 = "";
if (!r36) {
const r39 = 0 < r21.length;
let r7 = 0;
let r15 = "";
let r40 = "";
if (r39) {
do {
const r33 = r21[r7];
const r8 = r7 + 1;
const r24 = r15 + `
${r33}: ${r21[r8].micros / 1000}`;
const calls = r21[r8].calls;
const r47 = calls == null;
const r48 = r7;
let r49 = "";
if (!r47) {
const r50 = 0 < calls.length;
let r0 = 0;
let r27 = "";
let r51 = "";
if (r50) {
do {
const r52 = calls[r0];
const r1 = r0 + 1;
r27 = r27 + `
| ${r52}: ${calls[r1].micros / 1000}` + prettyPrintTrace_(calls[r1].calls, "| | ");
r0 = r0 + 2;
length = calls.length;
r51 = r27;
} while (r0 < length);
}
r49 = r51;
}
r15 = r24 + r49;
r7 = r48 + 2;
length2 = r21.length;
r40 = r15;
} while (r7 < length2);
}
r37 = r40;
}
r11 = r37;
}
return r11;
})(_trace == null ? void 0 : _trace[0]);
r10 = r9;
if (r9 != null) {
break L5;
}
} catch ($e) {}
return a0._trace != null ? a0._trace.join(" -> ") : "???";
}
return r10;
}
export function getReadyPayloadByteSizeAnalytics(a0) {
if (Math.random() > 0.01) {
return void 0;
}
const r33 = Date.now();
const { guilds, merged_presences } = a0;
let merged_members = a0.merged_members;
const { read_state, private_channels, user_guild_settings } = a0;
let user_settings = a0.user_settings;
let user_settings_proto = a0.user_settings_proto;
let experiments = a0.experiments;
let guild_experiments = a0.guild_experiments;
const { relationships, users } = a0;
let r36 = _objectWithoutProperties(a0, _excluded);
const r18 = [];
let c19987_0 = r18;
const r15 = [];
let c19987_1 = r15;
const r14 = [];
let c19987_2 = r14;
const r13 = [];
let c19987_3 = r13;
const r12 = [];
let c19987_4 = r12;
const r37 = [];
let c19987_5 = r37;
const r11 = [];
let c19987_6 = r11;
const r38 = [];
let c19987_7 = r38;
guilds.forEach((guild) => {
if (!guild.unavailable) {
let properties = guild.properties;
if (properties == null) {
properties = {};
}
const { features, ...rest } = properties;
const { threads, guild_scheduled_events, ...rest2 } = guild;
c19987_0.push(guild.data_mode === "partial" ? guild.partial_updates.channels : guild.channels);
c19987_1.push(guild.data_mode === "partial" ? guild.partial_updates.roles : guild.roles);
c19987_2.push(guild.data_mode === "partial" ? guild.partial_updates.emojis : guild.emojis);
c19987_3.push(threads);
c19987_4.push(guild.data_mode === "partial" ? guild.partial_updates.stickers : guild.stickers);
c19987_5.push(features);
c19987_6.push(guild_scheduled_events);
c19987_7.push(rest2, rest);
}
});
const r29 = JSON;
let r42 = merged_presences?.friends;
if (r42 == null) {
r42 = [];
}
const r45 = {
presences_size: r29.stringify(r42).length,
users_size: JSON.stringify(users).length,
read_states_size: JSON.stringify(read_state).length,
private_channels_size: JSON.stringify(private_channels).length,
user_settings_size: null,
experiments_size: null,
user_guild_settings_size: null,
relationships_size: null,
remaining_data_size: null,
guild_channels_size: null,
guild_members_size: null,
guild_presences_size: null,
guild_roles_size: null,
guild_emojis_size: null,
guild_threads_size: null,
guild_stickers_size: null,
guild_events_size: null,
guild_features_size: null,
guild_remaining_data_size: null,
size_metrics_duration_ms: null
};
const r58 = JSON;
if (user_settings == null) {
user_settings = "";
}
const length = r58.stringify(user_settings).length;
if (user_settings_proto == null) {
user_settings_proto = "";
}
r45.user_settings_size = length + user_settings_proto.length;
const r64 = JSON;
if (experiments == null) {
experiments = [];
}
const length2 = r64.stringify(experiments).length;
const r68 = JSON;
if (guild_experiments == null) {
guild_experiments = [];
}
r45.experiments_size = length2 + r68.stringify(guild_experiments).length;
r45.user_guild_settings_size = JSON.stringify(user_guild_settings).length;
r45.relationships_size = JSON.stringify(relationships).length;
const r81 = JSON;
if (r36 == null) {
r36 = {};
}
r45.remaining_data_size = r81.stringify(r36).length;
r45.guild_channels_size = JSON.stringify(r18).length;
const r89 = JSON;
if (merged_members == null) {
merged_members = [];
}
r45.guild_members_size = r89.stringify(merged_members).length;
const r93 = JSON;
let r96 = merged_presences?.guilds;
if (r96 == null) {
r96 = [];
}
r45.guild_presences_size = r93.stringify(r96).length;
r45.guild_roles_size = JSON.stringify(r15).length;
r45.guild_emojis_size = JSON.stringify(r14).length;
r45.guild_threads_size = JSON.stringify(r13).length;
r45.guild_stickers_size = JSON.stringify(r12).length;
r45.guild_events_size = JSON.stringify(r11).length;
r45.guild_features_size = JSON.stringify(r37).length;
r45.guild_remaining_data_size = JSON.stringify(r38).length;
r45.size_metrics_duration_ms = Date.now() - r33;
return r45;
}
export function logGatewayConnected({ socket, altGateway, gatewayUrl, now }) {
AnalyticsUtils.track(AnalyticEvents.GATEWAY_CONNECTED, {
num_failed_connect_attempts: socket.failedConnectAttempts,
gateway_url: gatewayUrl,
assigned_to_alt_gateway: altGateway.isAssignedToAltGateway(),
did_fall_back_from_alt_gateway: altGateway.getDidFallBack(),
is_reconnect: socket.hasConnectedOnce,
is_fast_connect: socket.isFastConnect,
duration_ms_since_first_connect_attempt: now - socket.firstConnectAttemptStartTime,
duration_ms_since_connect_attempt_start: now - socket.connectionStartTime
}, {
logEventProperties: true
});
}
export function createResumeAnalytics(a0) {
return {
connectTime: a0 == null ? 0 : a0,
numEvents: 0,
largestWaitTime: 0,
dispatchTime: 0,
totalWaitTime: 0,
initialWaitTime: 0,
startTime: performance.now(),
lastUpdateTime: performance.now()
};
}
export function logResumeAnalytics(a0) {
const currentUser = UserStore.getCurrentUser();
const r15 = currentUser == null ? void 0 : currentUser.isStaff();
if (!(r15 ? !r15 : Math.random() < 0.5)) {
AnalyticsUtils.track(AnalyticEvents.CONNECTION_RESUMED, {
connect_time_ms: a0.connectTime,
resume_time_ms: Math.floor(performance.now() - a0.startTime),
num_events: a0.numEvents,
largest_wait_time_ms: Math.floor(a0.largestWaitTime),
initial_wait_time_ms: Math.floor(a0.initialWaitTime),
total_wait_time_ms: Math.floor(a0.totalWaitTime),
total_dispatch_time_ms: Math.floor(a0.dispatchTime)
}, {
logEventProperties: true
});
}
}
+311
View File
@@ -0,0 +1,311 @@
// Metro module 12700 (f12701).
import { DISPATCHER_IDEAL_TIME_LIMIT_MS } from "./DispatcherWorkConstants";
import Logger from "../debug/Logger";
import { createDispatcherWorkScheduler } from "./DispatcherWorkScheduler.native";
import { createResumeAnalytics, getReadyPayloadByteSizeAnalytics, logReadyPayloadReceived, logResumeAnalytics } from "./GatewaySocketAnalytics";
import { WorkSchedulerTelemetryTiming, WorkSchedulerTelemetryMeasurement } from "./WorkSchedulerTelemetry";
import ConnectionState from "./ConnectionState";
import Module589 from "../../_bundle/Module589";
import ActionBatcher from "./ActionBatcher";
let c8750_5 = new Logger("GatewaySocket");
let c8750_6 = new Set(["INITIAL_GUILD", "READY"]);
let c8750_7 = new Set(["READY", "INITIAL_GUILD"]);
let c8750_8 = new Set(["READY", "READY_SUPPLEMENTAL", "RESUMED"]);
let c8750_9 = new Set(["READY", "INITIAL_GUILD", "READY_SUPPLEMENTAL", "RESUMED", "VOICE_CHANNEL_SELECT", "VOICE_STATE_UPDATE", "VOICE_SERVER_UPDATE", "RTC_CONNECTION_STATE", "RTC_CONNECTION_VIDEO", "RTC_CONNECTION_CLIENT_CONNECT", "RTC_CONNECTION_PING", "MEDIA_SESSION_JOINED", "MEDIA_ENGINE_PERMISSION", "SESSIONS_REPLACE", "STREAM_CREATE", "STREAM_SERVER_UPDATE", "STREAM_DELETE", "STREAM_UPDATE"]);
let c8750_10 = {
NotStarted: 0,
0: "NotStarted",
Loading: 1,
1: "Loading",
Loaded: 2,
2: "Loaded"
};
let c8750_11 = {};
class GatewaySocketDispatcher {
scheduler = createDispatcherWorkScheduler();
queue = [];
paused = true;
resumeAnalytics = createResumeAnalytics();
getDispatchHandler = null;
flush = (a0) => {
let Loaded2, status2;
if (this.paused) {
return true;
}
const r10 = performance.now();
const r5 = 0 < this.queue.length;
let r2 = 0;
let r24 = this;
if (r5) {
const status = this.queue[0].status;
const Loaded = c8750_10.Loaded;
let r0 = 0;
r2 = 0;
r24 = this;
if (status === Loaded) {
do {
const r1 = r0 + 1;
const length = this.queue.length;
r2 = r1;
r24 = this;
if (!(r1 < length)) {
break;
}
status2 = this.queue[r1].status;
Loaded2 = c8750_10.Loaded;
r0 = r1;
r2 = r0;
r24 = this;
} while (status2 === Loaded2);
}
}
if (r2 === 0) {
return true;
}
const r40 = r24.queue.splice(0, r2);
const r42 = r24.dispatchMultiple(r40, a0);
if (r42) {
r24.scheduler.telemetry.timeEnd(WorkSchedulerTelemetryTiming.TIME_TO_QUEUE_EMPTY);
}
const r15 = performance.now() - r10;
if (r15 > DISPATCHER_IDEAL_TIME_LIMIT_MS && !r42) {
c8750_5.log(`Dispatched ${r40.length} messages in ${r15}ms`);
}
return r42;
};
constructor(a0) {
this.socket = a0;
}
hasStuffToDispatchNow() {
return this.queue.length > 0 && this.queue[0].status === c8750_10.Loaded;
}
processFirstQueuedDispatch(a0) {
const r3 = [];
if (this.queue.length > 0 && a0.has(this.queue[0].type)) {
while (this.queue[0].status === c8750_10.Loaded) {
r3.push(this.queue.shift());
if (!(this.queue.length > 0)) {
break;
}
if (!a0.has(this.queue[0].type)) {
break;
}
}
}
this.dispatchMultiple(r3);
}
unpauseDispatchQueue() {
this.paused = false;
for (const item of this.queue) {
this.maybePreload(item);
}
this.flush();
}
receiveDispatch(a0, a1, a2) {
if (this.getDispatchHandler == null) {
throw Error("getDispatchHandler needs to be passed in first!");
}
const r4 = {
data: a0,
type: a1,
compressionAnalytics: a2,
status: c8750_10.NotStarted,
preloadPromise: null,
preloadedData: null
};
this.queue.push(r4);
if (!this.maybePreload(r4)) {
this.scheduleFlush(a1);
}
}
maybePreload(a0) {
let c19980_0 = a0;
if (this.paused && !c8750_6.has(a0.type)) {
return false;
}
if (a0.status === c8750_10.NotStarted) {
const dispatchHandler = this.getDispatchHandler(a0.type);
const preloadPromise = dispatchHandler == null ? void 0 : dispatchHandler.preload(a0.data);
a0.status = preloadPromise == null ? c8750_10.Loaded : c8750_10.Loading;
a0.preloadPromise = preloadPromise;
if (preloadPromise != null) {
preloadPromise.then((result) => {
c19980_0.preloadedData = result;
c19980_0.status = c8750_10.Loaded;
this.scheduleFlush(c19980_0.type);
}).catch((a0) => this.socket.resetSocketOnDispatchError({
error: a0,
action: c19980_0.type
}));
return true;
}
}
return false;
}
scheduleFlush(a0) {
if (!this.paused) {
const r9 = c8750_7.has(a0);
const scheduler = this.scheduler;
if (r9) {
scheduler.clearWorkTimeout();
this.flush();
} else if (!scheduler.hasWorkScheduled) {
this.scheduler.requestWorkTimeout(this.flush);
}
if (c8750_9.has(a0)) {
this.scheduler.markCriticalWorkScheduled();
}
}
}
getDispatchTimings() {
return c8750_11;
}
getSchedulerTelemetry() {
return this.scheduler.telemetry;
}
getIsSchedulerBackgrounded() {
return this.scheduler.isBackgrounded;
}
toggleRequestIdleCallback(a0) {
this.scheduler.toggleRequestIdleCallback(a0);
}
getIsRequestIdleCallbackEnabled() {
return this.scheduler.isRequestIdleCallbackEnabled;
}
dispatchMultiple(a0, c19981_2) {
let c19981_0, c19981_5;
if (a0.length === 0) {
return true;
}
const type = "none";
let c19981_4 = false;
this.scheduler.telemetry.measure(WorkSchedulerTelemetryMeasurement.COUNT_INITIAL_DISPATCHS_LENGTH, a0.length);
L9: {
try {
c19981_5 = [];
if (this.socket.connectionState === ConnectionState.RESUMING) {
Module589.Emitter.pause(150);
}
c19981_0 = 0;
Module589.Emitter.batched(() => {
let length;
const r8 = 0 < a0.length;
let r1 = 0;
if (r8) {
do {
const r14 = a0[r1];
type = r14.type;
let r25 = c19981_4;
const r0 = r1;
if (!r25) {
r25 = c8750_8.has(r14.type);
}
c19981_4 = r25;
const r28 = performance.now();
this.dispatchOne(r14);
c19981_0 = performance.now() - r28;
const type2 = r14.type;
const r22 = c19981_0;
let r38 = c8750_11[type2];
if (r38 == null) {
r38 = [0, 0];
}
const [r41, r42] = r38;
c8750_11[type2] = [(r41 * r42 + r22) / (r42 + 1), r42 + 1];
const r7 = c19981_2 == null;
let r49 = false;
if (!r7) {
const r50 = a0[r0];
const r52 = a0.length - 1;
const r53 = r0 < r52 ? a0[r0 + 1] : null;
let r55 = c19981_2 == null ? void 0 : c19981_2.timeRemaining();
if (r55 == null) {
r55 = 0;
}
const type3 = r50.type;
const type4 = r53?.type;
r49 = c19981_2 != null && r55 <= 0 && !(type3 === type4) && r0 !== r52;
}
const r61 = r0 + 1;
if (r49) {
c19981_5 = a0.slice(r61);
if (!(c19981_2 != null && c19981_2.timeRemaining() <= 0)) {
break;
}
this.scheduler.telemetry.timeTrack(WorkSchedulerTelemetryTiming.TIME_OVER_DEADLINE, c19981_2.timeSinceExpiration);
break;
}
length = a0.length;
r1 = r61;
} while (r1 < length);
}
ActionBatcher.flush();
});
if (c19981_4) {
Module589.Emitter.resume();
}
if (c19981_5.length > 0) {
this.scheduler.telemetry.measure(WorkSchedulerTelemetryMeasurement.COUNT_DISPATCHES_LEFT_AFTER_YIELD, c19981_5.length);
const queue = this.queue;
queue.unshift.apply(queue, [...c19981_5]);
this.scheduler.requestWorkTimeout(this.flush, true);
break L9;
}
} catch ($e) {
this.socket.resetSocketOnDispatchError({
error: $e,
action: type
});
}
return true;
}
return false;
}
dispatchOne({ data, type: type2, compressionAnalytics, preloadedData }) {
const lastUpdateTime = performance.now();
if (this.socket.connectionState === ConnectionState.RESUMING) {
const initialWaitTime = lastUpdateTime - this.resumeAnalytics.lastUpdateTime;
if (this.resumeAnalytics.numEvents === 0) {
this.resumeAnalytics.initialWaitTime = initialWaitTime;
} else if (initialWaitTime > this.resumeAnalytics.largestWaitTime) {
this.resumeAnalytics.largestWaitTime = initialWaitTime;
}
const resumeAnalytics = this.resumeAnalytics;
resumeAnalytics.totalWaitTime = resumeAnalytics.totalWaitTime + initialWaitTime;
this.resumeAnalytics.lastUpdateTime = lastUpdateTime;
const resumeAnalytics2 = this.resumeAnalytics;
resumeAnalytics2.numEvents = resumeAnalytics2.numEvents + 1;
}
ActionBatcher.flush(type2, data);
if (type2 === "READY") {
const readyPayloadByteSizeAnalytics = getReadyPayloadByteSizeAnalytics(data);
const dispatchHandler3 = this.getDispatchHandler(type2);
if (dispatchHandler3 != null) {
dispatchHandler3.dispatch(data, type2, preloadedData);
}
logReadyPayloadReceived(this.socket, data, lastUpdateTime, compressionAnalytics, readyPayloadByteSizeAnalytics);
} else if (type2 === "RESUMED") {
const dispatchHandler2 = this.getDispatchHandler(type2);
if (dispatchHandler2 != null) {
dispatchHandler2.dispatch(data, type2, preloadedData);
}
logResumeAnalytics(this.resumeAnalytics);
this.socket.handleResumeDispatched();
this.resumeAnalytics = createResumeAnalytics();
} else {
const dispatchHandler = this.getDispatchHandler(type2);
if (dispatchHandler != null) {
dispatchHandler.dispatch(data, type2, preloadedData);
}
}
if (this.socket.connectionState === ConnectionState.RESUMING) {
const resumeAnalytics3 = this.resumeAnalytics;
resumeAnalytics3.dispatchTime = resumeAnalytics3.dispatchTime + (performance.now() - lastUpdateTime);
}
}
clear() {
this.paused = false;
this.queue.length = 0;
}
}
export default GatewaySocketDispatcher;
+178
View File
@@ -0,0 +1,178 @@
// Metro module 12696 (f12697).
import RTCRegionStore from "../../stores/RTCRegionStore";
import { EventEmitter } from "../../_bundle/EventEmitter_652";
import * as _GatewaySocketOpcode from "./GatewaySocketOpcode";
import SnowflakeUtils from "../../utils/SnowflakeUtils";
class GatewaySocketOpCodes extends EventEmitter {
presenceUpdate(a0, a1, a2, a3) {
this.send(_GatewaySocketOpcode.Opcode.PRESENCE_UPDATE, {
status: a0,
since: a1,
activities: a2,
afk: a3
});
}
voiceStateUpdate({ guildId = null, channelId = null, selfMute = false, selfDeaf = false, selfVideo = false, preferredRegion = null, preferredRegions = null, videoStreamParameters = null, flags = 0 }) {
const r6 = {
guild_id: guildId,
channel_id: channelId,
self_mute: selfMute,
self_deaf: selfDeaf,
self_video: selfVideo,
flags
};
if (channelId != null && RTCRegionStore.shouldIncludePreferredRegion()) {
r6.preferred_region = preferredRegion;
r6.preferred_regions = preferredRegions;
}
if (videoStreamParameters != null) {
r6.tracks = videoStreamParameters == null ? void 0 : videoStreamParameters.map((videoStreamParameter) => ({
type: videoStreamParameter.type,
rid: videoStreamParameter.rid,
quality: videoStreamParameter.quality
}));
}
this.send(_GatewaySocketOpcode.Opcode.VOICE_STATE_UPDATE, r6);
}
voiceServerPing() {
this.send(_GatewaySocketOpcode.Opcode.VOICE_SERVER_PING, null);
}
requestGuildMembers(a0, a1) {
this.send(_GatewaySocketOpcode.Opcode.REQUEST_GUILD_MEMBERS, {
guild_id: a0,
query: a1.query,
limit: a1.limit,
user_ids: a1.userIds,
presences: a1.presences
});
}
searchRecentMembers(a0, a1) {
let query = a1.query;
let continuationToken = a1.continuationToken;
const send = this.send;
const SEARCH_RECENT_MEMBERS = _GatewaySocketOpcode.Opcode.SEARCH_RECENT_MEMBERS;
if (query == null) {
query = "";
}
if (continuationToken == null) {
continuationToken = null;
}
send.call(this, SEARCH_RECENT_MEMBERS, {
guild_id: a0,
query,
continuation_token: continuationToken
});
}
updateGuildSubscriptions(a0) {
let subscriptions = {};
let c19978_0 = 0;
SnowflakeUtils.keys(a0).forEach((item) => {
const r5 = a0[item];
const length = JSON.stringify([item, r5]).length;
if (c19978_0 + length > 15360) {
this.send(_GatewaySocketOpcode.Opcode.GUILD_SUBSCRIPTIONS_BULK, {
subscriptions
});
subscriptions = {};
c19978_0 = 0;
}
subscriptions[item] = r5;
c19978_0 = c19978_0 + length;
});
if (c19978_0 > 0) {
this.send(_GatewaySocketOpcode.Opcode.GUILD_SUBSCRIPTIONS_BULK, {
subscriptions
});
}
}
callConnect(a0) {
this.send(_GatewaySocketOpcode.Opcode.CALL_CONNECT, {
channel_id: a0
});
}
streamCreate(a0, a1, a2, preferred_region = null) {
this.send(_GatewaySocketOpcode.Opcode.STREAM_CREATE, {
type: a0,
guild_id: a1,
channel_id: a2,
preferred_region
});
}
streamWatch(a0) {
this.send(_GatewaySocketOpcode.Opcode.STREAM_WATCH, {
stream_key: a0
});
}
streamPing(a0) {
this.send(_GatewaySocketOpcode.Opcode.STREAM_PING, {
stream_key: a0
});
}
streamDelete(a0) {
this.send(_GatewaySocketOpcode.Opcode.STREAM_DELETE, {
stream_key: a0
});
}
streamSetPaused(a0, a1) {
this.send(_GatewaySocketOpcode.Opcode.STREAM_SET_PAUSED, {
stream_key: a0,
paused: a1
});
}
requestForumUnreads(a0, a1, a2) {
this.send(_GatewaySocketOpcode.Opcode.REQUEST_FORUM_UNREADS, {
guild_id: a0,
channel_id: a1,
threads: a2.map((item) => ({
thread_id: item.threadId,
ack_message_id: item.ackMessageId
}))
});
}
requestSoundboardSounds(a0) {
this.send(_GatewaySocketOpcode.Opcode.REQUEST_SOUNDBOARD_SOUNDS, {
guild_ids: a0
});
}
requestLastMessages(a0, a1) {
this.send(_GatewaySocketOpcode.Opcode.REQUEST_LAST_MESSAGES, {
guild_id: a0,
channel_ids: a1
});
}
getDeletedEntityIdsNotMatchingHash(a0, a1, a2, a3, a4) {
this.send(_GatewaySocketOpcode.Opcode.GET_DELETED_ENTITY_IDS_NOT_MATCHING_HASH, {
guild_id: a0,
channel_ids_hash: a1,
role_ids_hash: a2,
emoji_ids_hash: a3,
sticker_ids_hash: a4
});
}
triggerGuildChannelResync(a0, a1) {
this.send(_GatewaySocketOpcode.Opcode.GUILD_CHANNELS_RESYNC, {
guild_id: a0,
obfuscated_channel_ids: a1
});
}
requestChannelInfo(a0, a1) {
this.send(_GatewaySocketOpcode.Opcode.REQUEST_CHANNEL_INFO, {
guild_id: a0,
fields: a1
});
}
requestChannelMemberCount(a0, a1) {
this.send(_GatewaySocketOpcode.Opcode.REQUEST_CHANNEL_MEMBER_COUNT, {
guild_id: a0,
channel_id: a1
});
}
remoteCommand(a0, a1) {
this.send(_GatewaySocketOpcode.Opcode.REMOTE_COMMAND, {
target_session_id: a0,
payload: a1
});
}
}
export default GatewaySocketOpCodes;
export const Opcode = _GatewaySocketOpcode.Opcode;
+68
View File
@@ -0,0 +1,68 @@
// Metro module 12697 (f12698).
const r9 = {
DISPATCH: 0,
0: "DISPATCH",
HEARTBEAT: 1,
1: "HEARTBEAT",
IDENTIFY: 2,
2: "IDENTIFY",
PRESENCE_UPDATE: 3,
3: "PRESENCE_UPDATE",
VOICE_STATE_UPDATE: 4,
4: "VOICE_STATE_UPDATE",
VOICE_SERVER_PING: 5,
5: "VOICE_SERVER_PING",
RESUME: 6,
6: "RESUME",
RECONNECT: 7,
7: "RECONNECT",
REQUEST_GUILD_MEMBERS: 8,
8: "REQUEST_GUILD_MEMBERS",
INVALID_SESSION: 9,
9: "INVALID_SESSION",
HELLO: 10,
10: "HELLO",
HEARTBEAT_ACK: 11,
11: "HEARTBEAT_ACK",
CALL_CONNECT: 13,
13: "CALL_CONNECT",
GUILD_SUBSCRIPTIONS: 14,
14: "GUILD_SUBSCRIPTIONS",
STREAM_CREATE: 18,
18: "STREAM_CREATE",
STREAM_DELETE: 19,
19: "STREAM_DELETE",
STREAM_WATCH: 20,
20: "STREAM_WATCH",
STREAM_PING: 21,
21: "STREAM_PING",
STREAM_SET_PAUSED: 22,
22: "STREAM_SET_PAUSED",
REQUEST_GUILD_APPLICATION_COMMANDS: 24,
24: "REQUEST_GUILD_APPLICATION_COMMANDS",
REQUEST_FORUM_UNREADS: 28,
28: "REQUEST_FORUM_UNREADS",
REMOTE_COMMAND: 29,
29: "REMOTE_COMMAND",
GET_DELETED_ENTITY_IDS_NOT_MATCHING_HASH: 30,
30: "GET_DELETED_ENTITY_IDS_NOT_MATCHING_HASH",
REQUEST_SOUNDBOARD_SOUNDS: 31,
31: "REQUEST_SOUNDBOARD_SOUNDS",
REQUEST_LAST_MESSAGES: 34,
34: "REQUEST_LAST_MESSAGES",
SEARCH_RECENT_MEMBERS: 35,
35: "SEARCH_RECENT_MEMBERS",
GUILD_SUBSCRIPTIONS_BULK: 37,
37: "GUILD_SUBSCRIPTIONS_BULK",
GUILD_CHANNELS_RESYNC: 38,
38: "GUILD_CHANNELS_RESYNC",
REQUEST_CHANNEL_MEMBER_COUNT: 39,
39: "REQUEST_CHANNEL_MEMBER_COUNT",
QOS_HEARTBEAT: 40,
40: "QOS_HEARTBEAT",
UPDATE_TIME_SPENT_SESSION_ID: 41,
41: "UPDATE_TIME_SPENT_SESSION_ID",
REQUEST_CHANNEL_INFO: 43,
43: "REQUEST_CHANNEL_INFO"
};
export { r9 as Opcode };
@@ -0,0 +1,69 @@
// Metro module 12691 (f12692).
import AuthenticationStore from "../../stores/AuthenticationStore";
import Logger from "../debug/Logger";
import GatewaySocket from "./GatewaySocket";
import LocalPresenceStateManager from "./LocalPresenceStateManager";
import LocalVoiceStateManager from "./LocalVoiceStateManager";
import DiscordAppState_native from "../app_state/DiscordAppState.native";
import AnalyticsUtils from "../../utils/AnalyticsUtils";
import { describeConnectionReasons } from "./RequestGatewaySocket";
import { isDesktop } from "../../utils/PlatformUtils";
import DiscordNative from "../../lib/DiscordNative";
import NetworkUtils from "../../utils/NetworkUtils";
import Dispatcher from "../../Dispatcher";
let c8745_4 = new Logger("ConnectionStore");
let c8745_5 = new GatewaySocket();
let c8745_6 = new LocalPresenceStateManager(c8745_5);
const localVoiceStateManager = new LocalVoiceStateManager(c8745_5);
c8745_5.handleIdentify = () => {
const token = AuthenticationStore.getToken();
c8745_4.verbose("handleIdentify called", {
hasToken: token != null
});
if (token == null) {
return null;
}
const state = DiscordAppState_native.getState();
const installationForTracking = AuthenticationStore.getInstallationForTracking();
return {
token,
properties: {
...AnalyticsUtils.getSuperProperties(),
client_app_state: state,
is_fast_connect: false,
gateway_connect_reasons: describeConnectionReasons(),
...installationForTracking != null ? {
installation_id: installationForTracking
} : {}
},
presence: c8745_6.getInitialState()
};
};
if (isDesktop()) {
DiscordNative.powerMonitor.on("resume", () => {
c8745_5.expeditedHeartbeat(5000, "power monitor resumed");
});
}
NetworkUtils.addOfflineCallback(() => {
c8745_5.networkStateChange(15000, "network detected offline.", false);
});
NetworkUtils.addOnlineCallback(() => {
c8745_5.networkStateChange(5000, "network detected online.");
});
c8745_5.on("disconnect", (a0) => {
Dispatcher.dispatch({
type: "CONNECTION_CLOSED",
code: a0.code,
reason: a0.reason
});
});
c8745_5.on("close", (a0) => {
Dispatcher.dispatch({
type: "CONNECTION_INTERRUPTED",
code: a0.code,
reason: a0.reason
});
});
export { c8745_5 as socket };
export { c8745_6 as localPresenceState };
export { localVoiceStateManager as localVoiceState };
@@ -0,0 +1,19 @@
// Metro module 12709 (f12710).
import { NativeModules } from "react-native";
import { isAndroid } from "../../utils/PlatformUtils";
import Module12710 from "../../_bundle/Module12710";
export function supportsZstd() {
let supportsZstd2;
if (isAndroid()) {
supportsZstd2 = Module12710.getConstants().supportsZstd;
} else {
supportsZstd2 = NativeModules.DCDCompressionManager?.supportsZstd;
if (supportsZstd2 == null) {
supportsZstd2 = false;
}
}
return supportsZstd2;
}
export function createZstdContextWeb() {
throw new Error("Attempting to use createZstdContextWeb in a native context. Use MobileGatewayCompressionHandler instead.");
}
@@ -0,0 +1,34 @@
// Metro module 12731 (f12732).
import SelfPresenceStore from "../../stores/SelfPresenceStore";
import StateManager from "../../lib/StateManager";
import rateLimit from "../../lib/rateLimit";
class LocalPresenceStateManager extends StateManager {
switchingAccounts = false;
didCommit = rateLimit(5, 20000, this.emitPresenceUpdate.bind(this));
constructor(a0) {
super(false);
this.socket = a0;
}
getInitialState() {
return SelfPresenceStore.getLocalPresence();
}
getNextState() {
return SelfPresenceStore.getLocalPresence();
}
shouldCommit() {
return this.socket.isSessionEstablished();
}
emitPresenceUpdate(a0) {
this.socket.presenceUpdate(a0.status, a0.since, a0.activities, a0.afk);
}
handleConnectionOpen() {
this.update({}, !this.switchingAccounts);
this.switchingAccounts = false;
}
handleAccountSwitch() {
this.switchingAccounts = true;
this.reset();
this.emitPresenceUpdate(this.getState());
}
}
export default LocalPresenceStateManager;
+102
View File
@@ -0,0 +1,102 @@
// Metro module 12734 (f12735).
import RunningGameStore_native from "../game_detection/RunningGameStore.native";
import ApplicationStreamingStore from "../../stores/ApplicationStreamingStore";
import ChannelStore from "../../stores/ChannelStore";
import MediaEngineStore from "../../stores/MediaEngineStore";
import RTCRegionStore from "../../stores/RTCRegionStore";
import { ApplicationStreamStates, ChannelTypes, VoiceFlags } from "../../Constants";
import StateManager from "../../lib/StateManager";
import { ClipsAllowVoiceRecording } from "../user_settings/UserSettings";
import { setFlag } from "../../_bundle/Module1384";
import { isClipsEnabled, isDecoupledClipsEnabled } from "../clips/isClipsEnabled";
class LocalVoiceStateManager extends StateManager {
constructor(a0) {
super();
this.socket = a0;
}
get guildId() {
return this.getState().guildId;
}
get channelId() {
return this.getState().channelId;
}
computeVoiceFlags() {
const r19 = setFlag(0, VoiceFlags.ALLOW_VOICE_RECORDING, ClipsAllowVoiceRecording.getSetting());
let r23 = isClipsEnabled() && (ApplicationStreamingStore.getCurrentUserActiveStream()?.state === ApplicationStreamStates.ACTIVE || ApplicationStreamingStore.getCurrentUserActiveStream()?.state === ApplicationStreamStates.PAUSED);
const r37 = isDecoupledClipsEnabled() && RunningGameStore_native.getVisibleGame()?.windowHandle != null;
const CLIPS_ENABLED = VoiceFlags.CLIPS_ENABLED;
if (!r23) {
r23 = r37;
}
return setFlag(r19, CLIPS_ENABLED, r23);
}
getInitialState() {
return {
guildId: null,
channelId: null,
selfMute: MediaEngineStore.isSelfMute(),
selfDeaf: MediaEngineStore.isSelfDeaf(),
selfVideo: MediaEngineStore.isVideoEnabled(),
preferredRegion: null,
preferredRegions: null,
videoStreamParameters: null,
flags: 0
};
}
getNextState(a0) {
return {
guildId: a0.guildId,
channelId: a0.channelId,
selfMute: MediaEngineStore.isSelfMute(),
selfDeaf: MediaEngineStore.isSelfDeaf(),
selfVideo: MediaEngineStore.isVideoEnabled(),
preferredRegion: RTCRegionStore.getPreferredRegion(),
preferredRegions: RTCRegionStore.getPreferredRegions(),
videoStreamParameters: MediaEngineStore.getVideoStreamParameters(),
flags: this.computeVoiceFlags()
};
}
shouldCommit() {
return this.socket.isSessionEstablished();
}
didCommit({ guildId: guildId2, channelId: channelId2, selfMute, selfDeaf, selfVideo, preferredRegion, preferredRegions, videoStreamParameters, flags = 0 }) {
if (selfVideo) {
if (ChannelStore.getChannel(channelId2)?.type === ChannelTypes.GUILD_STAGE_VOICE) {
this.socket.voiceStateUpdate({
guildId: guildId2,
channelId: channelId2,
selfMute,
selfDeaf,
selfVideo,
preferredRegion,
preferredRegions,
videoStreamParameters,
flags
});
} else {
this.socket.voiceStateUpdate({
guildId: guildId2,
channelId: channelId2,
selfMute,
selfDeaf,
selfVideo,
preferredRegion,
preferredRegions,
flags
});
}
} else {
this.socket.voiceStateUpdate({
guildId: guildId2,
channelId: channelId2,
selfMute,
selfDeaf,
selfVideo,
preferredRegion,
preferredRegions,
flags
});
}
}
}
export default LocalVoiceStateManager;
+8
View File
@@ -0,0 +1,8 @@
// Metro module 12727 (f12728).
let c8768_0 = false;
export function getIsPaused() {
return c8768_0;
}
export function setIsPaused(a0) {
c8768_0 = a0;
}
@@ -0,0 +1,33 @@
// Metro module 6694 (f6695).
import NewUserStore from "../nuf/NewUserStore";
import GatewayConnectionStore from "./GatewayConnectionStore";
import Dispatcher from "../../Dispatcher";
function $mk78948($env) {
return () => (0, $env[0])();
}
let c4293_2;
const processCallbacks = function processCallbacks() {
if (NewUserStore.getType() == null) {
c4293_2.forEach((item) => {
let env25968;
const r1 = env25968 = {};
env25968[0] = item;
setImmediate($mk78948(r1));
});
c4293_2 = [];
}
};
c4293_2 = [];
Dispatcher.subscribe("CONNECTION_OPEN", processCallbacks);
Dispatcher.subscribe("CONNECTION_RESUMED", processCallbacks);
Dispatcher.subscribe("NUF_COMPLETE", processCallbacks);
export function addPostConnectionCallback(a0) {
if (GatewayConnectionStore.isConnectedOrOverlay() && NewUserStore.getType() == null) {
let env15863;
const r9 = env15863 = {};
env15863[0] = a0;
setImmediate($mk78948(r9));
} else {
c4293_2.push(a0);
}
}
@@ -0,0 +1,42 @@
// Metro module 12729 (f12730).
import { createApexExperiment } from "../experiments/apex/index";
import * as _PrivateChannelHidingExperimentCache from "./PrivateChannelHidingExperimentCache";
const apexExperiment = createApexExperiment({
name: "2026-02-private-channel-hiding",
kind: "user",
defaultConfig: {
enableObfuscation: false,
enableIntegrityCheck: false
},
variations: {
1: {
enableObfuscation: true,
enableIntegrityCheck: false
},
2: {
enableObfuscation: true,
enableIntegrityCheck: true
},
3: {
enableObfuscation: false,
enableIntegrityCheck: false
}
}
});
export const getCachedPrivateChannelObfuscation = _PrivateChannelHidingExperimentCache.getCachedPrivateChannelObfuscation;
export const PRIVATE_CHANNEL_OBFUSCATION_KEY = _PrivateChannelHidingExperimentCache.PRIVATE_CHANNEL_OBFUSCATION_KEY;
export function isChannelMetadataObfuscationEnabled(a0) {
return apexExperiment.getConfig({
location: a0
}).enableObfuscation;
}
export function useIsChannelMetadataObfuscationEnabled(a0) {
return apexExperiment.useConfig({
location: a0
}).enableObfuscation;
}
export function isChannelMetadataIntegrityCheckEnabled(a0) {
return apexExperiment.getConfig({
location: a0
}).enableIntegrityCheck;
}
@@ -0,0 +1,7 @@
// Metro module 12730 (f12731).
import { Storage } from "../../_bundle/Module595";
let c8770_2 = "private_channel_obfuscation";
export const PRIVATE_CHANNEL_OBFUSCATION_KEY = "private_channel_obfuscation";
export function getCachedPrivateChannelObfuscation() {
return Storage.get(c8770_2) != null;
}
+127
View File
@@ -0,0 +1,127 @@
// Metro module 675 (f676).
import { AnalyticEvents } from "../../Constants";
import { requestSafeIdleCallback } from "../../_bundle/Module696";
import AnalyticsUtils from "../../utils/AnalyticsUtils";
let _excluded, c583_6, c583_7, stopRequest;
const setRequestedBy = function setRequestedBy(a0) {
c583_7.size > 0;
c583_6 = false;
let r9 = c583_7.get(a0);
if (r9 == null) {
r9 = 0;
}
c583_7.set(a0, r9 + 1);
const r18 = `BRIDGE:${a0}`;
let r20 = c583_7.get(r18);
if (r20 == null) {
r20 = 0;
}
const r21 = r20 - 1;
if (r21 <= 0) {
c583_7.delete(r18);
} else {
c583_7.set(r18, r21);
}
c583_7.size > 0;
};
stopRequest = function stopRequest(a0) {
c583_7.size > 0;
c583_6 = false;
let r9 = c583_7.get(a0);
if (r9 == null) {
r9 = 0;
}
const r11 = r9 - 1;
if (r11 <= 0) {
c583_7.delete(a0);
} else {
c583_7.set(a0, r11);
}
c583_7.size > 0;
};
_excluded = ["COLD_START"];
c583_6 = true;
c583_7 = new Map();
export function isRequested() {
return c583_7.size > 0 || c583_6;
}
export function recordStartHeadlessTask() {
c583_6 = false;
}
export function describeConnectionReasons() {
const r6 = [...c583_6 ? _excluded : [], ...c583_7.keys()].sort();
return r6.length > 0 ? r6.join(",") : "NO_REASONS";
}
export { setRequestedBy };
export function startBridgeTo(a0) {
const bridge_token = `BRIDGE:${a0}`;
let c12442_1 = performance.now();
c583_7.size > 0;
c583_6 = false;
let r18 = c583_7.get(bridge_token);
if (r18 == null) {
r18 = 0;
}
c583_7.set(bridge_token, r18 + 1);
c583_7.size > 0;
requestSafeIdleCallback(() => {
if (c583_7.has(bridge_token)) {
AnalyticsUtils.track(AnalyticEvents.GATEWAY_BRIDGE_TIMEOUT, {
bridge_token,
cleared_after: performance.now() - c12442_1
});
}
c583_7.size > 0;
c583_6 = false;
let r28 = c583_7.get(bridge_token);
if (r28 == null) {
r28 = 0;
}
const r30 = r28 - 1;
if (r30 <= 0) {
c583_7.delete(bridge_token);
} else {
c583_7.set(bridge_token, r30);
}
c583_7.size > 0;
}, {
timeout: 5000
});
}
export { stopRequest };
export async function withRequest(c23824_0, c23824_1) {
let r18;
let c23824_4;
let c23824_5 = 0;
let c28667_0;
try {
c28667_0 = c23824_0;
c23824_5 = 1;
setRequestedBy(c23824_0);
r18 = await c23824_1();
c23824_5 = 0;
(0, stopRequest)(c28667_0);
} catch ($e) {
const r22 = $e;
let r8 = r22;
c23824_4 = r22;
if (c23824_5 !== 0) {
while (true) {
try {
const r56 = c23824_4;
c23824_5 = 0;
(0, stopRequest)(c28667_0);
throw r56;
} catch (r52) {
r8 = r52;
c23824_4 = r52;
if (c23824_5 === 0) {
break;
}
}
}
}
throw r8;
}
return r18;
}
+138
View File
@@ -0,0 +1,138 @@
// Metro module 12704 (f12705).
import { cloneDeep } from "../../_bundle/Module12";
const r20 = {
LONGER_DISPATCH: "longer_dispatch",
EXCEEDED_MAX_CONSECUTIVE_FLUSHES: "exceeded_max_consecutive_flushes",
FIRED_DUE_TO_MAX_TIMEOUT: "fired_due_to_max_timeout",
SKIP_IDLE_CALLBACK_DUE_TO_BACKGROUNDED: "skip_idle_callback_due_to_backgrounded"
};
const r25 = {
TIME_TO_FIRE_IDLE_CALLBACK: "time_to_fire_idle_callback",
TIME_TO_QUEUE_EMPTY: "time_to_flush_all_work",
TIME_OVER_DEADLINE: "time_over_deadline",
DEADLINE_INITIAL_TIME_REMAINING: "initial_time_of_deadline"
};
const r30 = {
COUNT_DISPATCHES_LEFT_AFTER_YIELD: "count_dispatches_left_after_yield",
COUNT_FLUSH_BEFORE_QUEUE_EMPTY: "count_flush_before_queue_empty",
COUNT_INITIAL_DISPATCHS_LENGTH: "count_initial_dispatches_length"
};
const r13 = Object;
const r34 = {};
r34[r25.TIME_TO_FIRE_IDLE_CALLBACK] = null;
r34[r25.TIME_TO_QUEUE_EMPTY] = null;
r34[r25.TIME_OVER_DEADLINE] = null;
r34[r25.DEADLINE_INITIAL_TIME_REMAINING] = null;
let c8754_3 = r13.freeze(r34);
const r39 = Object;
const r41 = {};
r41[r25.TIME_TO_FIRE_IDLE_CALLBACK] = [0, 0];
r41[r25.TIME_TO_QUEUE_EMPTY] = [0, 0];
r41[r25.TIME_OVER_DEADLINE] = [0, 0];
r41[r25.DEADLINE_INITIAL_TIME_REMAINING] = [0, 0];
let c8754_4 = r39.freeze(r41);
const r50 = Object;
const r52 = {};
r52[r30.COUNT_FLUSH_BEFORE_QUEUE_EMPTY] = [0, 0];
r52[r30.COUNT_DISPATCHES_LEFT_AFTER_YIELD] = [0, 0];
r52[r30.COUNT_INITIAL_DISPATCHS_LENGTH] = [0, 0];
let c8754_5 = r50.freeze(r52);
const r60 = Object;
const r62 = {};
r62[r20.LONGER_DISPATCH] = 0;
r62[r20.EXCEEDED_MAX_CONSECUTIVE_FLUSHES] = 0;
r62[r20.FIRED_DUE_TO_MAX_TIMEOUT] = 0;
r62[r20.SKIP_IDLE_CALLBACK_DUE_TO_BACKGROUNDED] = 0;
let c8754_6 = r60.freeze(r62);
export { r20 as WorkSchedulerTelemetryEvent };
export { r25 as WorkSchedulerTelemetryTiming };
export { r30 as WorkSchedulerTelemetryMeasurement };
export class WorkSchedulerTelemetry {
constructor() {
const r11 = {
__proto__: new.target.prototype,
_timeTracking: cloneDeep(c8754_3),
_timingStats: null,
_measurements: null,
_eventCounts: null,
_enabled: false
};
r11._timingStats = cloneDeep(c8754_4);
r11._measurements = cloneDeep(c8754_5);
r11._eventCounts = cloneDeep(c8754_6);
return r11;
}
reset() {
this._timeTracking = cloneDeep(c8754_3);
this._timingStats = cloneDeep(c8754_4);
this._measurements = cloneDeep(c8754_5);
this._eventCounts = cloneDeep(c8754_6);
}
clearTime(a0) {
this._timeTracking[a0] = null;
}
_storeTimeValue(a0, a1) {
const [r11, r12] = this._timingStats[a0];
this._timingStats[a0] = [(r11 * r12 + a1) / (r12 + 1), r12 + 1];
}
time(a0) {
if (this._enabled) {
this._timeTracking[a0] = performance.now();
}
}
timeEnd(a0) {
if (this._enabled) {
const r4 = this._timeTracking[a0];
if (r4 != null) {
this._storeTimeValue(a0, performance.now() - r4);
this._timeTracking[a0] = null;
}
}
}
timeTrack(a0, a1) {
if (this._enabled) {
this._storeTimeValue(a0, a1);
}
}
measure(a0, a1) {
if (this._enabled) {
const [r12, r13] = this._measurements[a0];
this._measurements[a0] = [(r12 * r13 + a1) / (r13 + 1), r13 + 1];
}
}
track(a0) {
if (this._enabled) {
const _eventCounts = this._eventCounts;
_eventCounts[a0] = _eventCounts[a0] + 1;
}
}
toggleTelemetry(a0) {
this._enabled = a0;
}
get isTelemetryEnabled() {
return this._enabled;
}
generateTelemetry() {
const r13 = Object.entries(this._timingStats).reduce((acc, item) => {
const [r8, r7] = item;
const [r36] = r7;
acc[`avg_${r8}`] = `${r36.toFixed(2)}ms`;
return acc;
}, {});
const r20 = Object.entries(this._measurements).reduce((acc, item) => {
const [r8, r7] = item;
const [r35] = r7;
acc[`avg_${r8}`] = `${r35.toFixed(2)}`;
return acc;
}, {});
return {
...Object.entries(this._eventCounts).reduce((acc, item) => {
const [r8, r7] = item;
acc[`count_${r8}`] = `${r7}`;
return acc;
}, {}),
...r13,
...r20
};
}
}
@@ -0,0 +1,8 @@
// Metro module 12695 (f12696).
export default function createWebSocket(a0, a1) {
return new WebSocket(a0, a1, {
headers: {
Origin: window.GLOBAL_ENV.NATIVE_WEBSOCKET_ORIGIN
}
});
};
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,20 @@
// Metro module 12699 (f12700).
import { NativeModules } from "react-native";
import { isAndroid } from "../../utils/PlatformUtils";
import Module502 from "../../_bundle/Module502";
export default function getCachedUseAltGateway() {
let r11;
if (isAndroid()) {
let useAltGateway = Module502.getConstants().useAltGateway;
if (useAltGateway == null) {
useAltGateway = false;
}
r11 = useAltGateway;
} else {
r11 = NativeModules.DCDFastConnectManager.useAltGateway;
if (r11 == null) {
r11 = false;
}
}
return r11;
};
+187
View File
@@ -0,0 +1,187 @@
// Metro module 15 (f16).
import "../../../utils/checkEnv";
import { AppState, NativeModules } from "react-native";
import { VERSION_TO_FORCE_RESYNCING_ALL_DATA } from "../../app_database/modules/KvCacheVersionConstants";
import Logger from "../../debug/Logger";
import * as _PlatformUtils from "../../../utils/PlatformUtils";
import Module502 from "../../../_bundle/Module502";
import { getSuperProperties } from "../../../_bundle/Module503";
import { describeConnectionReasons } from "../RequestGatewaySocket";
import { getClientCapabilities } from "../GatewayCapabilities";
import { isCacheEnabled } from "../../cache/isCacheEnabled.native";
import Module12710 from "../../../_bundle/Module12710";
import getCachedUseAltGateway_native from "../getCachedUseAltGateway.native";
import createWebSocket_android from "../createWebSocket.android";
import Module10 from "../../../_bundle/Module10";
import TTITracker from "../../tti_analytics/TTITracker";
let c36_7, c36_8;
export function createFastConnectSocket() {
if (window.WebSocket != null) {
const r12 = _PlatformUtils.isAndroid() ? Module12710.getConstants().supportsZstd : NativeModules.DCDCompressionManager.supportsZstd;
const r16 = r12 ? "zstd-stream" : "zlib-stream";
let GATEWAY_ALT_ENDPOINT = window.GLOBAL_ENV.GATEWAY_ALT_ENDPOINT;
if (!(getCachedUseAltGateway_native() && GATEWAY_ALT_ENDPOINT != null)) {
GATEWAY_ALT_ENDPOINT = window.GLOBAL_ENV.GATEWAY_ENDPOINT;
}
let c12108_1;
const gateway = `${GATEWAY_ALT_ENDPOINT}/?encoding=json&v=${window.GLOBAL_ENV.API_VERSION}&compress=${r16}`;
c36_7.log("[FAST CONNECT] " + gateway);
let c12108_0 = Date.now();
const webSocket_android = createWebSocket_android(gateway);
const r60 = parseFloat(webSocket_android._socketId);
if (isNaN(r60)) {
c36_7.log("[FAST CONNECT] Unable to create socketId from NaN value ", webSocket_android._socketId);
} else {
const isAndroid = _PlatformUtils.isAndroid();
if (r12) {
if (isAndroid) {
Module12710.enableZstdStreamSupport(r60);
} else {
NativeModules.DCDCompressionManager.enableZstdStreamSupport(r60, 0);
}
} else if (isAndroid) {
Module12710.enableZlibStreamSupport(r60);
} else {
NativeModules.DCDCompressionManager.enableZlibStreamSupport(r60);
}
const state = {
open: false,
gateway,
identify: false,
messages: [],
clientState: null,
userId: null
};
c12108_1 = state;
webSocket_android.onopen = () => {
Module10.mark("🌐", "Fastconnect socket opened");
const r9 = Date.now() - c12108_0;
c36_7.log(`connected and identified in ${r9}ms didIdentify:${c12108_1.identify}`);
c12108_1.open = true;
};
const onerror = () => {
Module10.mark("🌐", "Fastconnect socket close");
window._ws = null;
};
webSocket_android.onerror = onerror;
webSocket_android.onclose = onerror;
webSocket_android.onmessage = (a0) => {
Module10.mark("🌐", "Fastconnect socket message");
c12108_1.messages.push(a0);
};
window._ws = {
ws: webSocket_android,
state
};
Module10.mark("🌐", "Fastconnect socket created");
}
} else {
c36_7.log("Skipping fast_connect because `window.WebSocket` does not exist.");
}
}
c36_7 = new Logger("FAST CONNECT");
c36_7.info("initial app state (import time)", AppState.currentState);
c36_8 = null;
createFastConnectSocket();
export function closeFastConnectSocket() {
if (window._ws != null) {
window._ws.ws.close();
window._ws = null;
c36_8 = null;
}
}
export function getLastFastConnectIdentifyUserId() {
return c36_8;
}
export function identifyWebSocket() {
if (window._ws != null) {
TTITracker.beginFastConnect.measure(() => {
let installation_id, useChannelObfuscation2;
const token = TTITracker.loadFastConnectNativeModule.measure(() => {
let r10;
if (_PlatformUtils.isAndroid()) {
let token = Module502.getConstants().token;
if (token == null) {
token = null;
}
r10 = token;
} else {
r10 = NativeModules.DCDFastConnectManager.token;
}
return r10;
});
if (token != null && token !== "") {
const _ws = window._ws;
const { ws, state } = _ws;
const _socketId = ws._socketId;
let r15 = _PlatformUtils.isAndroid() ? Module502.getConstants().userId : NativeModules.DCDFastConnectManager.userId;
c36_8 = r15 == null ? null : r15;
state.userId = r15 == null ? null : r15;
if (r15 == null) {
r15 = null;
}
c36_7.info("prepareIdentify: app state: ", AppState.currentState);
if (_PlatformUtils.isAndroid()) {
let analyticsInstallation = Module502.getConstants().analyticsInstallation;
if (analyticsInstallation == null) {
analyticsInstallation = null;
}
installation_id = analyticsInstallation;
} else {
installation_id = NativeModules.DCDFastConnectManager.analyticsInstallation;
}
const properties = {
...getSuperProperties(),
client_app_state: AppState.currentState,
is_fast_connect: true,
gateway_connect_reasons: describeConnectionReasons(),
...installation_id != null ? {
installation_id
} : {}
};
if (_PlatformUtils.isAndroid()) {
let useChannelObfuscation = Module502.getConstants().useChannelObfuscation;
if (useChannelObfuscation == null) {
useChannelObfuscation = false;
}
useChannelObfuscation2 = useChannelObfuscation;
} else {
useChannelObfuscation2 = NativeModules.DCDFastConnectManager.useChannelObfuscation;
if (useChannelObfuscation2 == null) {
useChannelObfuscation2 = false;
}
}
const r62 = {
token,
properties,
capabilities: getClientCapabilities({
useChannelObfuscation: useChannelObfuscation2
}),
client_state: {
guild_versions: {}
}
};
const r100 = JSON.stringify({
op: 2,
d: r62
});
if (_PlatformUtils.isAndroid()) {
let r116 = r15 == null ? void 0 : r15.toString();
if (r116 == null) {
r116 = null;
}
Module502.prepareIdentify(r116, r100, parseFloat(_socketId), isCacheEnabled() ? VERSION_TO_FORCE_RESYNCING_ALL_DATA : void 0);
} else {
NativeModules.DCDFastConnectManager.prepareIdentify(r15, r100, _socketId, isCacheEnabled() ? VERSION_TO_FORCE_RESYNCING_ALL_DATA : null);
}
const client_state = r62.client_state;
state.identify = true;
state.clientState = client_state;
} else {
c36_7.log("Skipping fast_connect because we could not find a token to connect with.");
}
});
} else {
c36_7.log("Skipping identifyWebSocket because socket is null");
}
}
@@ -0,0 +1,15 @@
// Metro module 13614 (f13615).
import { useEffect } from "react";
import DiscordAppState_native from "../app_state/DiscordAppState.native";
import { setRequestedBy, stopRequest } from "./RequestGatewaySocket";
export function useRequestGatewaySocket(a0) {
const canUIRequestGatewaySocket = DiscordAppState_native.useCanUIRequestGatewaySocket();
useEffect(() => {
if (canUIRequestGatewaySocket) {
setRequestedBy(a0);
return () => {
stopRequest(a0);
};
}
}, [a0, canUIRequestGatewaySocket]);
}