Skip to content
Open
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 31 additions & 15 deletions src/transports/ipc.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,33 +13,49 @@ const OPCodes = {
PONG: 4,
};

function getIPCPath(id) {
function getIPCPath(id, snap) {
if (process.platform === 'win32') {
return `\\\\?\\pipe\\discord-ipc-${id}`;
}
const { env: { XDG_RUNTIME_DIR, TMPDIR, TMP, TEMP } } = process;
const prefix = XDG_RUNTIME_DIR || TMPDIR || TMP || TEMP || '/tmp';
return `${prefix.replace(/\/$/, '')}/discord-ipc-${id}`;
return `${prefix.replace(/\/$/, '')}${snap ? '/snap.discord' : ''}/discord-ipc-${id}`;
}

function getIPC(id = 0) {
return new Promise((resolve, reject) => {
const path = getIPCPath(id);
const onerror = () => {
if (id < 10) {
resolve(getIPC(id + 1));
} else {
reject(new Error('Could not connect'));
}
};
function makeSocket(path) {
return new Promise((res, rej) => {
const sock = net.createConnection(path, () => {
sock.removeListener('error', onerror);
resolve(sock);
sock.removeListener('error', rej);
res(sock);
});
sock.once('error', onerror);
sock.once('error', rej);
});
}

async function getIPC() {
// Attempt a connection the usual way first.
const connect = async snap => {
for (let i = 0; i < 10; i++) {
try {
return await makeSocket(getIPCPath(i, snap));
} catch (_) {
// Something went wrong with this connection. Go to the next iteration.
}
}
};
let res = await connect(false);
if (res) return res;

// Handle snap connections.
if (process.platform === "linux") {
res = await connect(true);
if (res) return res;
}

// If all else fails, throw an error.
throw new Error('Could not connect');
}

async function findEndpoint(tries = 0) {
if (tries > 30) {
throw new Error('Could not find endpoint');
Expand Down