Skip to content

Commit

Permalink
Awaiting for a connection to Discord client before anything else
Browse files Browse the repository at this point in the history
  • Loading branch information
liddack committed May 3, 2018
1 parent 995fc30 commit 9a57f7a
Show file tree
Hide file tree
Showing 6 changed files with 99 additions and 37 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,6 @@ typings/
.vscode

# JSHint local settings
.jshintrc
.jshintrc

image_assets
42 changes: 20 additions & 22 deletions core.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
'use strict'

const DiscordRP = require('discord-rich-presence'),
client = new DiscordRP('427863248734388224'),
log = require('fancy-log'),
jsdom = require('jsdom'),
{ JSDOM } = jsdom
const log = require('fancy-log'),
jsdom = require('jsdom'),
{ JSDOM } = jsdom

let playback = {
filename: '',
Expand Down Expand Up @@ -35,13 +33,13 @@ const states = {
}
}

const updatePresence = res => {
const updatePresence = (res, rpc) => {
let { document } = new JSDOM(res.body).window
playback.filename = document.getElementById('file').textContent
playback.state = document.getElementById('state').textContent
playback.duration = sanitizeTime(document.getElementById('durationstring').textContent)
playback.position = sanitizeTime(document.getElementById('positionstring').textContent)

playback.filename = document.getElementById('file').textContent
playback.state = document.getElementById('state').textContent
playback.duration = sanitizeTime(document.getElementById('durationstring').textContent)
playback.position = sanitizeTime(document.getElementById('positionstring').textContent)

let payload = {
state: playback.duration + ' total',
Expand All @@ -65,32 +63,32 @@ const updatePresence = res => {
break;
}

if ( (playback.state !== playback.prevState) || (
playback.state === '2' &&
convert(playback.position) !== convert(playback.prevPosition) + 1
) ) {
client.updatePresence(payload)
log.info('INFO: Presence update sent:\n' +
if ((playback.state !== playback.prevState) || (
playback.state === '2' &&
convert(playback.position) !== convert(playback.prevPosition) + 5
)) {
rpc.setActivity(payload)
log.info('INFO: Presence update sent: ' +
`CONNECTED - ${states[playback.state].string} - ${playback.position} / ${playback.duration} - ${playback.filename}`
)
}

playback.prevState = playback.state
playback.prevPosition = playback.position
playback.prevPosition = playback.position
return true
}

const convert = time => {
let parts = time.split(':'),
seconds = parseInt(parts[parts.length-1]),
minutes = parseInt(parts[parts.length-2]),
seconds = parseInt(parts[parts.length - 1]),
minutes = parseInt(parts[parts.length - 2]),
hours = (parts.length > 2) ? parseInt(parts[0]) : 0
return ((hours * 60 * 60) + (minutes * 60) + seconds)
}

const sanitizeTime = time => {
if (time.split(':')[0] === '00') {
return time.substr(3, time.length-1)
return time.substr(3, time.length - 1)
}
return time
}
Expand Down
72 changes: 60 additions & 12 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,54 @@ const log = require('fancy-log')
log.info('INFO: Loading...')

const snekfetch = require('snekfetch'),
{ Client } = require('discord-rpc'),
core = require('./core'),
events = require('events'),
config = require('./config')
config = require('./config'),
clientID = '427863248734388224'

let mediaEmitter = new events.EventEmitter(),
active = false
active = false,
discordRPCLoop,
mpcServerLoop,
rpc

if (isNaN(config.port)) {
throw new Error('Port is empty or invalid! Please set a valid port number in \'config.js\' file.')
}

const uri = `https://localhost:${config.port}/variables.html`

log.info('INFO: Fully ready')
log.info('INFO: Listening on ' + uri)
log.info('INFO: Fully ready. Trying to connect to Discord client...')

mediaEmitter.on('CONNECTED', res => {
if (global.intloop._idleTimeout === 15000) {
clearInterval(global.intloop)
setInterval(checkMedia, 1000)
clearInterval(mpcServerLoop)
mpcServerLoop = setInterval(checkMedia, 5000)
if (!active) {
log.info('INFO: Connected to MPC-HC')
}
active = core(res)
active = core(res, rpc)
})

mediaEmitter.on('CONN_ERROR', code => {
log.error(`ERROR: Unable to connect to Media Player Classic on port ${config.port}. ` +
`Make sure MPC is running, Web Interface is enabled and the port set in 'config.js' file is correct.\n` + code)
log.error(`ERROR: Unable to connect to Media Player Classic on port ${config.port}. ` +
`Make sure MPC is running, Web Interface is enabled and the port set in 'config.js' file is correct.\n` + code)
if (active) {
process.exit()
process.exit(0)
}
clearInterval(mpcServerLoop)
mpcServerLoop = setInterval(checkMedia, 15000)
})

mediaEmitter.on('discordConnected', () => {
clearInterval(discordRPCLoop)
log.info('INFO: Connected to Discord. Listening MPC on ' + uri)
checkMedia()
mpcServerLoop = setInterval(checkMedia, 15000)
})

mediaEmitter.on('discordDisconnected', () => {
clearInterval(mpcServerLoop)
})

// Functions
Expand All @@ -47,4 +66,33 @@ function checkMedia() {
})
}

global.intloop = setInterval(checkMedia, 15000)
function initRPC(clientID) {
rpc = new Client({ transport: 'ipc' });

rpc.on('ready', () => {
clearInterval(discordRPCLoop)
mediaEmitter.emit('discordConnected')

rpc.transport.once('close', async () => {
await destroyRPC();
log.error('ERROR: Connection to Discord has closed. Trying again in 10 seconds...');
mediaEmitter.emit('discordDisconnected')
discordRPCLoop = setInterval(initRPC, 10000, clientID);
});
//rpc.setActivity(payload);
})

// Log in to the RPC Client, and check whether or not it errors.
rpc.login(clientID).catch(error => {
log.warn('WARN: Connection to Discord has failed. Trying again in 10 seconds...');
})
}

async function destroyRPC() {
if (!rpc) return;
await rpc.destroy();
rpc = null;
log.info('INFO: você destruiu o meu rpc');
}

discordRPCLoop = setInterval(initRPC, 10000, clientID);
9 changes: 7 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
"author": "angeloanan <[email protected]>",
"license": "MIT",
"dependencies": {
"@types/node": "^9.6.6",
"discord-rich-presence": "^0.0.6",
"discord-rpc": "^3.0.0-beta.10",
"fancy-log": "^1.3.2",
"jsdom": "^11.6.2",
"snekfetch": "^4.0.0-beta.0"
Expand Down
7 changes: 7 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,13 @@ discord-rich-presence@^0.0.6:
dependencies:
discord-rpc "^3.0.0-beta.8"

discord-rpc@^3.0.0-beta.10:
version "3.0.0-beta.10"
resolved "https://registry.yarnpkg.com/discord-rpc/-/discord-rpc-3.0.0-beta.10.tgz#d1178347a4b1e2cc574e206fdb5efc69348af398"
dependencies:
discord.js "github:discordjs/discord.js"
snekfetch "^3.5.8"

discord-rpc@^3.0.0-beta.8:
version "3.0.0-beta.9"
resolved "https://registry.yarnpkg.com/discord-rpc/-/discord-rpc-3.0.0-beta.9.tgz#6257ccbb2a7712111b58871e875ef41857812d85"
Expand Down

0 comments on commit 9a57f7a

Please sign in to comment.