Skip to content

Commit

Permalink
update rpc plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
wont-stream committed Sep 26, 2024
1 parent b04041e commit e440414
Show file tree
Hide file tree
Showing 10 changed files with 319 additions and 158 deletions.
1 change: 1 addition & 0 deletions build.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ for (const plugin of plugins) {
...repl._builtinLibs.map((m) => `node:${m}`),
"@neptune",
"@plugin",
"electron"
],
platform: "browser",
outfile,
Expand Down
Binary file modified bun.lockb
Binary file not shown.
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,9 @@
},
"devDependencies": {
"esbuild": "^0.18.20"
},
"dependencies": {
"@xhayper/discord-rpc": "^1.2.0",
"electron": "^32.1.2"
}
}
70 changes: 70 additions & 0 deletions plugins/DiscordRPC/src/_lib/Caches/MediaItemCache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { store } from "@neptune";
import { interceptPromise } from "../intercept/interceptPromise";
import getPlaybackControl from "../getPlaybackControl";

import { libTrace } from "../trace";

export class MediaItemCache {
current(playbackContext) {
const context = playbackContext ?? getPlaybackControl()?.playbackContext;
if (context?.actualProductId === undefined) return undefined;
return this.ensure(context.actualProductId);
}
async ensureTrack(itemId) {
const mediaItem = await this.ensure(itemId);
if (mediaItem?.contentType === "track") return mediaItem;
return undefined;
}
async ensureVideo(itemId) {
const mediaItem = await this.ensure(itemId);
if (mediaItem?.contentType === "video") return mediaItem;
return undefined;
}
async ensure(itemId) {
if (itemId === undefined) return undefined;

const mediaItem = this._cache[itemId];
if (mediaItem !== undefined) return mediaItem;

const mediaItems = store.getState().content.mediaItems;
for (const itemId in mediaItems) {
const item = mediaItems[itemId]?.item;
this._cache[itemId] = item;
}

if (this._cache[itemId] === undefined) {
const currentPage = window.location.pathname;

const loadedTrack = await interceptPromise(
() => neptune.actions.router.replace(`/track/${itemId}`),
["page/IS_DONE_LOADING"],
[],
)
.then(() => true)
.catch(
libTrace.warn.withContext(
`TrackItemCache.ensure failed to load track ${itemId}`,
),
);
// If we fail to load the track, maybe its a video, try that instead as a last ditch attempt
if (!loadedTrack) {
await interceptPromise(
() => neptune.actions.router.replace(`/video/${itemId}`),
["page/IS_DONE_LOADING"],
[],
).catch(
libTrace.warn.withContext(
`TrackItemCache.ensure failed to load video ${itemId}`,
),
);
}
neptune.actions.router.replace(currentPage);

const mediaItems = store.getState().content.mediaItems;
const trackItem = mediaItems[+itemId]?.item;
this._cache[itemId] = trackItem;
}

return this._cache[itemId];
}
}
3 changes: 3 additions & 0 deletions plugins/DiscordRPC/src/_lib/getPlaybackControl.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { store } from "@neptune";

export default () => store.getState()?.playbackControls ?? {};
32 changes: 32 additions & 0 deletions plugins/DiscordRPC/src/_lib/intercept/interceptPromise.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { intercept } from "@neptune";

export const interceptPromise = () => {
timeoutMs ??= 5000;
cancel ??= false;
let res;
let rej;
const p = new Promise((_res, _rej) => {
res = _res;
rej = _rej;
});
const unloadRes = intercept(
resActionType,
(payload) => {
res(payload);
if (cancel) return true;
},
true,
);
if (!rej) throw new Error("Rejection function is not defined");
const unloadRej = intercept(rejActionType, rej, true);
const timeout = setTimeout(
() => rej(`${rejActionType ?? resActionType}_TIMEOUT`),
timeoutMs,
);
trigger();
return p.finally(() => {
clearTimeout(timeout);
unloadRes();
unloadRej();
});
};
63 changes: 63 additions & 0 deletions plugins/DiscordRPC/src/_lib/trace.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { actions } from "@neptune";

export const Tracer = (source) => {
const createLogger = (logger) => {
const _logger = (...data) => {
logger(source, ...data);
return undefined;
};
_logger.withContext =
(context) =>
(...data) => {
logger(source, context, ...data);
return undefined;
};
return _logger;
};

const log = createLogger(console.log);
const warn = createLogger(console.warn);
const err = createLogger(console.error);
const debug = createLogger(console.debug);

const createMessager = (logger, messager, severity) => {
const _messager = (message) => {
logger(message);
messager({
message: `${source} - ${message}`,
category: "OTHER",
severity,
});
return undefined;
};
_messager.withContext = (context) => {
const loggerWithContext = logger.withContext(context);
return (message) => {
loggerWithContext(message);
let finalMessage = message;
if (message instanceof Error) finalMessage = message.message;
messager({
message: `${source}.${context} - ${message}`,
category: "OTHER",
severity,
});
return undefined;
};
};
return _messager;
};

return {
log,
warn,
err,
debug,
msg: {
log: createMessager(log, actions.message.messageInfo, "INFO"),
warn: createMessager(warn, actions.message.messageWarn, "WARN"),
err: createMessager(err, actions.message.messageError, "ERROR"),
},
};
};

export const libTrace = Tracer("[lib]");
30 changes: 30 additions & 0 deletions plugins/DiscordRPC/src/discord.native.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Client } from "@xhayper/discord-rpc";
import electron from "electron";

let rpcClient = null;
async function getClient() {
const isAvailable = rpcClient?.transport.isConnected && rpcClient.user;
if (isAvailable) return rpcClient;

if (rpcClient) await rpcClient.destroy();
rpcClient = new Client({ clientId: "1288341778637918208" });
await rpcClient.connect();

return rpcClient;
}

async function setActivity(event, activity) {
const client = await getClient();
if (!client.user) return;
if (!activity) return client.user.clearActivity();
return client.user.setActivity(activity);
}

async function cleanup() {
return rpcClient?.destroy();
}

electron.ipcMain.removeHandler("DISCORD_SET_ACTIVITY");
electron.ipcMain.removeHandler("DISCORD_CLEANUP");
electron.ipcMain.handle("DISCORD_SET_ACTIVITY", setActivity);
electron.ipcMain.handle("DISCORD_CLEANUP", cleanup);
Loading

0 comments on commit e440414

Please sign in to comment.