Init commit

This commit is contained in:
Lea 2024-05-19 16:57:26 +02:00
commit 20e08186d7
Signed by: Lea
GPG key ID: 1BAFFE8347019C42
12 changed files with 1462 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
node_modules/
out/

54
LICENSE Normal file
View file

@ -0,0 +1,54 @@
# 🏳️‍🌈 Opinionated Queer License v1.1
© Copyright [Lea](https://me.lea.pet)
## Permissions
The creators of this Work (“The Licensor”) grant permission
to any person, group or legal entity that doesn't violate the prohibitions below (“The User”),
to do everything with this Work that would otherwise infringe their copyright or any patent claims,
subject to the following conditions:
## Obligations
The User must give appropriate credit to the Licensor,
provide a copy of this license or a (clickable, if the medium allows) link to
[oql.avris.it/license/v1.1](https://oql.avris.it/license/v1.1),
and indicate whether and what kind of changes were made.
The User may do so in any reasonable manner,
but not in any way that suggests the Licensor endorses the User or their use.
## Prohibitions
No one may use this Work for prejudiced or bigoted purposes, including but not limited to:
racism, xenophobia, queerphobia, queer exclusionism, homophobia, transphobia, enbyphobia, misogyny.
No one may use this Work to inflict or facilitate violence or abuse of human rights as defined in the
[Universal Declaration of Human Rights](https://www.un.org/en/about-us/universal-declaration-of-human-rights).
No law enforcement, carceral institutions, immigration enforcement entities, military entities or military contractors
may use the Work for any reason. This also applies to any individuals employed by those entities.
No business entity where the ratio of pay (salaried, freelance, stocks, or other benefits)
between the highest and lowest individual in the entity is greater than 50 : 1
may use the Work for any reason.
No private business run for profit with more than a thousand employees
may use the Work for any reason.
Unless the User has made substantial changes to the Work,
or uses it only as a part of a new work (eg. as a library, as a part of an anthology, etc.),
they are prohibited from selling the Work.
That prohibition includes processing the Work with machine learning models.
## Sanctions
If the Licensor notifies the User that they have not complied with the rules of the license,
they can keep their license by complying within 30 days after the notice.
If they do not do so, their license ends immediately.
## Warranty
This Work is provided “as is”, without warranty of any kind, express or implied.
The Licensor will not be liable to anyone for any damages related to the Work or this license,
under any kind of legal claim as far as the law allows.

28
README.md Normal file
View file

@ -0,0 +1,28 @@
# Deezer Discord Presence
This script provides Discord Rich Presence for Deezer by fetching playback data from the KDE Browser Integration via DBus.
**This is a personal project** tailored to my needs, so you will likely have to put in some effort or mess with the source code to get it working. I don't expect anyone else to be interested in using this, but I'm happy to accept issues and pull requests regardless.
![Screenshot of the presence widget on my profile](./assets/presence.png)
### Running
```bash
pnpm install # Install dependencies
pnpm run build
pnpm run start
```
A systemd user service [deezer-rich-presence.service](./deezer-rich-presence.service) is provided, adjust the paths to your nodejs binary and the application directory and copy it to `~/.local/share/systemd/user/`.
Since I use Vencord with [arrpc](https://arrpc.openasar.dev/) (which runs separately from Discord in the background), the service runs fine on my machine while Discord is closed - However, if you use the default Discord client, you will likely see the service crash repeatedly unless Discord is running. \
I recommend using Vencord with arrpc instead of the default client as it is better in every regard than the stock client on Linux. Otherwise you'll have to deal with systemd stopping the service when it exits too frequently.
### How it works
This is a very specific setup but can easily be adapted to other browsers or software, as long as they provide `org.mpris.MediaPlayer2.Player`. Simply replace `org.kde.plasma.browser_integration` in `index.ts` with the appropriate name (can be found through `busctl --user list`). \
You'll likely want to replace the client ID too if you want to change the application name or artwork. The Rich Presence assets I use are in [app_assets/](./app_assets/).
Unfortunately, due to limitations with how this data is provided, this is not always reliable, especially when other media is playing in the same browser. For some reason, the length and progress timestamps are messed up too, but the latter usually works well enough™ to still be worth including. \
Ideally this information would be collected through a custom browser extension, but as those can't directly connect to IPC, extra complexity involving a separate desktop client would be required.

BIN
app_assets/deezer_logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

BIN
app_assets/icon_pause.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

BIN
app_assets/icon_play.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

BIN
assets/presence.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View file

@ -0,0 +1,10 @@
[Unit]
Description=Deezer Rich Presence
[Service]
Type=simple
ExecStart=/usr/bin/node /home/lea/git/deezer-rpc/out
Restart=on-failure
[Install]
WantedBy=default.target

24
package.json Normal file
View file

@ -0,0 +1,24 @@
{
"name": "deezer-rpc",
"version": "1.0.0",
"description": "",
"type": "module",
"main": "out/index.js",
"scripts": {
"dev": "rm -rf out && tsc-watch --onSuccess 'node out'",
"build": "rm -rf out && tsc",
"start": "node out"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/discord-rpc": "^4.0.8",
"tsc-watch": "^6.2.0",
"typescript": "^5.4.5"
},
"dependencies": {
"dbus-next": "^0.10.2",
"discord-rpc": "^4.0.1"
}
}

1084
pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load diff

151
src/index.ts Normal file
View file

@ -0,0 +1,151 @@
/**
* https://invent.kde.org/plasma/plasma-browser-integration/-/blob/master/dbus/org.mpris.MediaPlayer2.Player.xml?ref_type=heads
*/
import dbus from "dbus-next";
import RPC, { Presence } from "discord-rpc";
const CLIENT_ID = "1237419378383781949";
let rpcClient = new RPC.Client({ transport: "ipc" });
rpcClient.login({ clientId: CLIENT_ID, scopes: [] })
type PlaybackData = {
artUrl?: string,
album?: string,
artist?: string[],
title?: string,
length?: number,
position?: number,
playing: boolean,
paused?: boolean,
}
export enum ActivityType {
Playing = 0,
Listening = 2,
Watching = 3,
Competing = 5,
}
let playbackData: PlaybackData = { playing: false };
const bus: dbus.MessageBus = dbus.sessionBus();
let obj: dbus.ProxyObject;
let player: dbus.ClientInterface;
let props: dbus.ClientInterface;
async function run() {
while (true) {
try {
obj = await bus.getProxyObject("org.kde.plasma.browser_integration", "/org/mpris/MediaPlayer2");
player = obj.getInterface("org.mpris.MediaPlayer2.Player");
props = obj.getInterface("org.freedesktop.DBus.Properties");
break;
} catch(e) {
console.log("Failed to connect: " + e + "\nRetrying in 5000ms");
await new Promise(r => setTimeout(r, 5000));
}
}
async function fetchData() {
parseData("Metadata", (await props.Get("org.mpris.MediaPlayer2.Player", "Metadata")).value);
parseData("PlaybackStatus", (await props.Get("org.mpris.MediaPlayer2.Player", "PlaybackStatus")).value);
parseData("Position", (await props.Get("org.mpris.MediaPlayer2.Player", "Position")).value);
}
function parseData(prop: string, data: any) {
switch(prop) {
case 'Metadata': {
if (!data?.["xesam:url"]?.value?.startsWith("https://www.deezer.com/")) {
data = { playing: false };
return;
}
playbackData.artUrl = data?.["mpris:artUrl"]?.value;
playbackData.length = Number(data?.["mpris:length"]?.value) / 1000;
playbackData.album = data?.["xesam:album"]?.value;
playbackData.artist = data?.["xesam:artist"]?.value;
playbackData.title = data?.["xesam:title"]?.value;
break;
}
case 'PlaybackStatus': {
playbackData.playing = data == "Playing";
playbackData.paused = data == "Paused";
break;
}
case 'Position': {
playbackData.position = Number(data) / 1000;
break;
}
default: {
console.debug("Received data update for", prop, "- ignoring")
return;
}
}
console.log("Processed update for prop", prop);
}
await fetchData();
let interval: any;
await setPresence(true);
async function setPresence(manual: boolean = false) {
if (manual) {
if (typeof interval != "undefined") clearInterval(interval);
interval = setInterval(setPresence, 15000); // Regularly update to make sure Discord doesn't forget about us for some reason
}
console.log("Setting presence");
if (!playbackData.playing && !playbackData.paused) {
await rpcClient.clearActivity();
}
else {
const presence: Presence = {
details: playbackData.title?.slice(0, 128) ?? "(Unknown song)",
state: playbackData.artist?.join(", ").slice(0, 128) ?? "(Unknown artist)",
endTimestamp: playbackData.playing ? Date.now() + (playbackData.length! - playbackData.position!) : undefined,
largeImageKey: playbackData.artUrl ?? "deezer_logo",
largeImageText: `${playbackData.artist} - ${playbackData.title}`.slice(0, 128),
smallImageKey: playbackData.playing ? "icon_play" : playbackData.paused ? "icon_pause" : undefined,
smallImageText: playbackData.playing ? "Playing" : playbackData.paused ? "Paused" : undefined,
buttons: [
{ label: 'Play on Deezer', url: `https://www.deezer.com/search/${encodeURIComponent(`${playbackData.artist} - ${playbackData.title}`)}` },
],
type: ActivityType.Listening
} as any;
await rpcClient.setActivity(presence);
}
}
setInterval(() => playbackData.position && playbackData.position++, 1);
props.on('PropertiesChanged', (iface: string, changed: { [key: string]: any }[], invalidated: any[]) => {
for (let [prop, data] of Object.entries(changed)) {
parseData(prop, data.value);
}
setPresence(true);
});
// I have no idea what event to listen to to detect when the browser
// exits, so we poll it and enter the reconnect loop on error
async function pollStatus() {
try {
await props.Get("org.mpris.MediaPlayer2.Player", "PlaybackStatus");
setTimeout(pollStatus, 500);
} catch(e) {
console.log("Failed to poll status: " + e + "\nConsidering this connection dead");
if (interval) clearInterval(interval);
props.removeAllListeners();
playbackData = { playing: false };
await rpcClient.clearActivity();
// Restart everything on a new stack
setTimeout(run, 0);
}
}
await pollStatus();
}
run();

109
tsconfig.json Normal file
View file

@ -0,0 +1,109 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "ESNext", /* Specify what module code is generated. */
"rootDir": "./src", /* Specify the root folder within your source files. */
"moduleResolution": "Node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "./out", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}