Skip to content

Commit ed01560

Browse files
committed
v0.3.0 (Merge branch 'indev' after messing up)
2 parents b05f591 + b70640a commit ed01560

File tree

7 files changed

+1121
-1091
lines changed

7 files changed

+1121
-1091
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ Please note that this only works with [Discord desktop client](https://discordap
1414
![Enable the option "Listen on port"](https://cdn.discordapp.com/attachments/416273308540207116/428748994307424256/unknown.png)
1515

1616
2. Install [`Node.JS`](https://nodejs.org/en/download/current/) (we recommend using the latest version). Optional but better, also install [`Yarn`](https://yarnpkg.com/docs/install).
17-
3. Download this project as a .zip file, extract it and open a terminal window in the project directory. Otherwise, if you have [Git](https://git-scm.com/) installed, run:
17+
18+
3. [Download this project as a .zip file](https://github.com/angeloanan/MPC-DiscordRPC/archive/master.zip), extract it and open a terminal window in the project directory. Otherwise, if you have [Git](https://git-scm.com/) installed, run:
1819

1920
```sh
2021
git clone https://github.com/angeloanan/MPC-DiscordRPC.git && cd MPC-DiscordRPC

core.js

Lines changed: 31 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
1-
'use strict'
2-
31
const log = require('fancy-log'),
4-
jsdom = require('jsdom'),
5-
{ JSDOM } = jsdom
2+
jsdom = require('jsdom'),
3+
{ JSDOM } = jsdom;
64

75
// Discord Rich Presence has a string length limit of 128 characters.
86
// This little plugin (based on https://stackoverflow.com/a/43006978/7090367)
97
// helps by trimming strings up to a given length.
108
String.prototype.trimStr = function (length) {
11-
return this.length > length ? this.substring(0, length - 3) + "..." : this
12-
}
9+
return this.length > length ? this.substring(0, length - 3) + "..." : this;
10+
};
1311

1412
// Defines playback data fetched from MPC.
1513
let playback = {
@@ -20,7 +18,7 @@ let playback = {
2018
state: '',
2119
prevState: '',
2220
prevPosition: '',
23-
}
21+
};
2422

2523
// Defines strings and image keys according to the 'state' string
2624
// provided by MPC.
@@ -41,7 +39,7 @@ const states = {
4139
string: 'Playing',
4240
stateKey: 'play_small'
4341
}
44-
}
42+
};
4543

4644
/**
4745
* Sends Rich Presence updates to Discord client.
@@ -50,16 +48,16 @@ const states = {
5048
*/
5149
const updatePresence = (res, rpc) => {
5250
// Identifies which MPC fork is running.
53-
let mpcFork = res.headers.server.replace(' WebServer', '')
51+
const mpcFork = res.headers.server.replace(' WebServer', '');
5452

5553
// Gets a DOM object based on MPC Web Interface variables page.
56-
let { document } = new JSDOM(res.body).window
54+
const { document } = new JSDOM(res.body).window;
5755

5856
// Gets relevant info from the DOM object.
59-
playback.filename = document.getElementById('filepath').textContent.split("\\").pop().trimStr(128)
60-
playback.state = document.getElementById('state').textContent
61-
playback.duration = sanitizeTime(document.getElementById('durationstring').textContent)
62-
playback.position = sanitizeTime(document.getElementById('positionstring').textContent)
57+
playback.filename = document.getElementById('filepath').textContent.split("\\").pop().trimStr(128);
58+
playback.state = document.getElementById('state').textContent;
59+
playback.duration = sanitizeTime(document.getElementById('durationstring').textContent);
60+
playback.position = sanitizeTime(document.getElementById('positionstring').textContent);
6361

6462
// Prepares playback data for Discord Rich Presence.
6563
let payload = {
@@ -70,19 +68,19 @@ const updatePresence = (res, rpc) => {
7068
largeImageText: mpcFork,
7169
smallImageKey: states[playback.state].stateKey,
7270
smallImageText: states[playback.state].string
73-
}
71+
};
7472

7573
// Makes changes to payload data according to playback state.
7674
switch (playback.state) {
7775
case '-1': // Idling
78-
payload.state = states[playback.state].string
79-
payload.details = undefined
76+
payload.state = states[playback.state].string;
77+
payload.details = undefined;
8078
break;
8179
case '1': // Paused
82-
payload.state = playback.position + ' / ' + playback.duration
80+
payload.state = playback.position + ' / ' + playback.duration;
8381
break;
8482
case '2': // Playing
85-
payload.startTimestamp = (Date.now() / 1000) - convert(playback.position)
83+
payload.startTimestamp = (Date.now() / 1000) - convert(playback.position);
8684
break;
8785
}
8886

@@ -94,18 +92,18 @@ const updatePresence = (res, rpc) => {
9492
)) {
9593
rpc.setActivity(payload)
9694
.catch((err) => {
97-
log.error('ERROR: ' + err)
98-
})
95+
log.error('ERROR: ' + err);
96+
});
9997
log.info('INFO: Presence update sent: ' +
10098
`${states[playback.state].string} - ${playback.position} / ${playback.duration} - ${playback.filename}`
101-
)
99+
);
102100
}
103101

104102
// Replaces previous playback state and position for later comparison.
105-
playback.prevState = playback.state
106-
playback.prevPosition = playback.position
107-
return true
108-
}
103+
playback.prevState = playback.state;
104+
playback.prevPosition = playback.position;
105+
return true;
106+
};
109107

110108
/**
111109
* Simple and quick utility to convert time from 'hh:mm:ss' format to seconds.
@@ -116,9 +114,9 @@ const convert = time => {
116114
let parts = time.split(':'),
117115
seconds = parseInt(parts[parts.length - 1]),
118116
minutes = parseInt(parts[parts.length - 2]),
119-
hours = (parts.length > 2) ? parseInt(parts[0]) : 0
120-
return ((hours * 60 * 60) + (minutes * 60) + seconds)
121-
}
117+
hours = (parts.length > 2) ? parseInt(parts[0]) : 0;
118+
return ((hours * 60 * 60) + (minutes * 60) + seconds);
119+
};
122120

123121
/**
124122
* In case the given 'hh:mm:ss' formatted time string is less than 1 hour,
@@ -128,9 +126,9 @@ const convert = time => {
128126
*/
129127
const sanitizeTime = time => {
130128
if (time.split(':')[0] === '00') {
131-
return time.substr(3, time.length - 1)
129+
return time.substr(3, time.length - 1);
132130
}
133-
return time
134-
}
131+
return time;
132+
};
135133

136-
module.exports = updatePresence
134+
module.exports = updatePresence;

index.js

Lines changed: 37 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,106 +1,104 @@
1-
'use strict'
1+
const log = require('fancy-log');
22

3-
const log = require('fancy-log')
4-
5-
log.info('INFO: Loading...')
3+
log.info('INFO: Loading...');
64

75
const snekfetch = require('snekfetch'),
86
{ Client } = require('discord-rpc'),
97
updatePresence = require('./core'),
108
events = require('events'),
119
config = require('./config'),
12-
clientID = '427863248734388224'
10+
clientID = '427863248734388224';
1311

1412
let mediaEmitter = new events.EventEmitter(),
1513
active = false,
1614
discordRPCLoop,
1715
mpcServerLoop,
18-
rpc
16+
rpc;
1917

2018
// Checks if port set in config.js is valid.
2119
if (isNaN(config.port)) {
22-
throw new Error('Port is empty or invalid! Please set a valid port number in \'config.js\' file.')
20+
throw new Error('Port is empty or invalid! Please set a valid port number in \'config.js\' file.');
2321
}
2422

25-
const uri = `http://localhost:${config.port}/variables.html`
23+
const uri = `http://localhost:${config.port}/variables.html`;
2624

27-
log.info('INFO: Fully ready. Trying to connect to Discord client...')
25+
log.info('INFO: Fully ready. Trying to connect to Discord client...');
2826

2927
// When it succesfully connects to MPC Web Interface, it begins checking MPC
3028
// every 5 seconds, getting its playback data and sending it to Discord Rich Presence
3129
// through updatePresence() function from core.js.
3230
mediaEmitter.on('CONNECTED', res => {
33-
clearInterval(mpcServerLoop)
34-
mpcServerLoop = setInterval(checkMPCEndpoint, 5000)
31+
clearInterval(mpcServerLoop);
32+
mpcServerLoop = setInterval(checkMPCEndpoint, 5000);
3533
if (!active) {
36-
log.info(`INFO: Connected to ${res.headers.server}`)
34+
log.info(`INFO: Connected to ${res.headers.server}`);
3735
}
38-
active = updatePresence(res, rpc)
39-
})
36+
active = updatePresence(res, rpc);
37+
});
4038

4139
// When connection to MPC fails it attempts to connect
4240
// to MPC again every 15 seconds.
4341
mediaEmitter.on('CONN_ERROR', code => {
4442
log.error(`ERROR: Unable to connect to Media Player Classic on port ${config.port}. ` +
45-
`Make sure MPC is running, Web Interface is enabled and the port set in 'config.js' file is correct.\n` + code)
43+
`Make sure MPC is running, Web Interface is enabled and the port set in 'config.js' file is correct.\n` + code);
4644
// If MPC was previously connected (ie. MPC gets closed while script is running)
4745
// the whole process is killed and restarted by Forever in order to clean MPC Rich Presence
4846
// from user's profile, as destroyRPC() apparently can't do so.
4947
if (active) {
50-
log.warn('WARN: Killing process to clean Rich Presence from your profile...')
51-
process.exit(0)
48+
log.warn('WARN: Killing process to clean Rich Presence from your profile...');
49+
process.exit(0);
5250
}
5351
if (mpcServerLoop._onTimeout !== checkMPCEndpoint) {
54-
clearInterval(mpcServerLoop)
55-
mpcServerLoop = setInterval(checkMPCEndpoint, 15000)
52+
clearInterval(mpcServerLoop);
53+
mpcServerLoop = setInterval(checkMPCEndpoint, 15000);
5654
}
57-
})
55+
});
5856

5957
// If RPC successfully connects to Discord client,
6058
// it will attempt to connect to MPC Web Interface every 15 seconds.
6159
mediaEmitter.on('discordConnected', () => {
62-
clearInterval(discordRPCLoop)
63-
log.info('INFO: Connected to Discord. Listening MPC on ' + uri)
64-
checkMPCEndpoint()
65-
mpcServerLoop = setInterval(checkMPCEndpoint, 15000)
66-
})
60+
clearInterval(discordRPCLoop);
61+
log.info('INFO: Connected to Discord. Listening MPC on ' + uri);
62+
checkMPCEndpoint();
63+
mpcServerLoop = setInterval(checkMPCEndpoint, 15000);
64+
});
6765

6866
// If RPC gets disconnected from Discord Client,
6967
// it will stop checking MPC playback data.
7068
mediaEmitter.on('discordDisconnected', () => {
71-
clearInterval(mpcServerLoop)
72-
})
69+
clearInterval(mpcServerLoop);
70+
});
7371

7472
// Tries to connect to MPC Web Interface and,
7573
// if connected, fetches its data.
7674
function checkMPCEndpoint() {
7775
snekfetch.get(uri)
78-
.then(function (res) {
79-
mediaEmitter.emit('CONNECTED', res)
80-
})
81-
.catch(function (err) {
82-
mediaEmitter.emit('CONN_ERROR', err)
76+
.then(res => {
77+
mediaEmitter.emit('CONNECTED', res);
8378
})
79+
.catch(err => {
80+
mediaEmitter.emit('CONN_ERROR', err);
81+
});
8482
}
8583

8684
// Initiates a new RPC connection to Discord client.
8785
function initRPC(clientID) {
88-
rpc = new Client({ transport: 'ipc' })
86+
rpc = new Client({ transport: 'ipc' });
8987
rpc.on('ready', () => {
90-
clearInterval(discordRPCLoop)
91-
mediaEmitter.emit('discordConnected')
88+
clearInterval(discordRPCLoop);
89+
mediaEmitter.emit('discordConnected');
9290
rpc.transport.once('close', async () => {
9391
await destroyRPC();
9492
log.error('ERROR: Connection to Discord client was closed. Trying again in 10 seconds...');
95-
mediaEmitter.emit('discordDisconnected')
93+
mediaEmitter.emit('discordDisconnected');
9694
discordRPCLoop = setInterval(initRPC, 10000, clientID);
9795
});
98-
})
96+
});
9997

10098
// Log in to the RPC server on Discord client, and check whether or not it errors.
101-
rpc.login(clientID).catch(error => {
99+
rpc.login(clientID).catch(() => {
102100
log.warn('WARN: Connection to Discord has failed. Trying again in 10 seconds...');
103-
})
101+
});
104102
}
105103

106104
// Destroys any active RPC connection.

0 commit comments

Comments
 (0)