Skip to content

Commit

Permalink
Improvements
Browse files Browse the repository at this point in the history
- Now supports all versions of Discord on Windows
- Less loops to find the process name
- Cleaned up lots of redundant code
  • Loading branch information
cwkhawand committed May 13, 2021
1 parent d423f91 commit 7e2d5b1
Show file tree
Hide file tree
Showing 7 changed files with 114 additions and 82 deletions.
72 changes: 57 additions & 15 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,24 @@ data = null;
console.log("This instance is running with the DEBUG argument. Errors will be logged to this console.")
}

// Register the RPC, necessary in order to show buttons
RPC.register(Application.clientID);

// Set the user presence
async function setPresence(){
try{
if(Growtopia.clientIsOpen){
data = await Growtopia.generateRPCData();
if(Growtopia.clientIsOpen){
Growtopia.generateRPCData()
.then(data => {
client.request('SET_ACTIVITY', {
pid: process.pid,
activity: data
}).catch(e=>Application.errorHandler(e));
}
}catch(e){
Application.errorHandler(e);
process.exit(0);
})
.catch(e => {
// Most likely, save.dat couldn't be accessed
Application.errorHandler(e);
process.exit(0);
})
}
}

Expand All @@ -50,9 +53,11 @@ data = null;
// Login to the client and if successful, set the presence
client.login({
clientId: Application.clientID
}).then(() => {
})
.then(() => {
setPresence();
}).catch(e => {
})
.catch(e => {
Application.errorHandler(e);
setTimeout(() => {
Discord.emit("start");
Expand All @@ -79,9 +84,11 @@ data = null;
// Login to the client and if successful, set the presence
client.login({
clientId: Application.clientID
}).then(() => {
})
.then(() => {
setPresence();
}).catch(e=>Application.errorHandler(e));
})
.catch(e=>Application.errorHandler(e));
});

// When Growtopia is closed, clear the Rich Presence or exit the application
Expand All @@ -96,15 +103,18 @@ data = null;
if(!Growtopia.clientIsOpen || data === null) return;

// Fetch new save.dat data
Growtopia.generateRPCData().then(newData => {
Growtopia.generateRPCData()
.then(newData => {
// If GrowID or World Name have chanced, set presence again
if(newData.details != data.details || newData.state != data.state){
setPresence();
}
}).catch(e=>Application.errorHandler(e));
})
.catch(e=>Application.errorHandler(e));
});

var stdin = process.openStdin();
// Support for command line input
let stdin = process.openStdin();
stdin.addListener("data", function(d) {
let input = d.toString().trim().split(":");
if(input[0] == "exec"){
Expand Down Expand Up @@ -134,4 +144,36 @@ data = null;
Growtopia.checkAppStatus();
Discord.checkAppStatus();
Application.checkForUpdates();
})();
})();


// Make sure all errors are handled, even uncaught ones
process.on('uncaughtException', function(e) {
console.log('An error has occured. More information is provided below if you have debugging turned on.');
try{
Application.errorHandler(e);
}catch(e){
// Make sure we don't go into an infinite loop if Application.errorHandler throws an exception
}
return;
});

process.on("unhandledRejection", async (e) => {
console.log('An error has occured. More information is provided below if you have debugging turned on.');
try{
Application.errorHandler(e);
}catch(e){
// Make sure we don't go into an infinite loop if Application.errorHandler throws an exception
}
return;
});

process.on('warning', function(e) {
console.log('An error has occured. More information is provided below if you have debugging turned on.');
try{
Application.errorHandler(e);
}catch(e){
// Make sure we don't go into an infinite loop if Application.errorHandler throws an exception
}
return;
});
5 changes: 1 addition & 4 deletions modules/Application.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,8 @@ var os = require('os');
class Application {
constructor() {
this.clientID = "841694148758208542";
this.version = "v1.5.2";
this.version = "v1.6.3";
this.debug = false;
this.device = {
isMacOS: os.platform() === 'darwin'
};
}

checkForUpdates(){
Expand Down
33 changes: 4 additions & 29 deletions modules/DiscordHelper.js
Original file line number Diff line number Diff line change
@@ -1,45 +1,20 @@
const exec = require('child_process').exec;
const findProcess = require('find-process');
const EventEmitter = require('events');
const Application = require('../modules/Application.js');
const System = require('../modules/System.js');

class DiscordHelper extends EventEmitter {
constructor(){
super();
// Discord client status
this.clientIsOpen = false;
}

async isOpen(){
if(Application.device.isMacOS) return await this.isOpenMacOS();
else return await this.isOpenWindows();
return await System.processExists('Discord', ["Discord", "Discord PTB", "Discord Canary", "Discord.exe", "Discord PTB.exe", "Discord Canary.exe"]);
}

async isOpenWindows(){
return new Promise((resolve, reject) => {
exec('tasklist', (err, stdout, stderr) => {
if(!stdout) resolve(false);
resolve(stdout.includes("Discord.exe"));
});
});
}

async isOpenMacOs(){
return new Promise((resolve, reject) => {
let isFound = findProcess('name', 'Discord').then(list => {
for (let ver of ['', ' PTB', ' Canary']) {
for (let process of list) {
if (process.name === 'Discord' + ver) {
return true;
}
}
}
return false;
})
resolve(isFound);
});
}

checkAppStatus(){
async checkAppStatus(){
let self = this;
(async function check(){
let clientIsOpen = await self.isOpen();
Expand Down
54 changes: 22 additions & 32 deletions modules/GrowtopiaHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,50 +2,34 @@ const exec = require('child_process').exec;
const findProcess = require('find-process');
const EventEmitter = require('events');
const fs = require('fs');
const Application = require('../modules/Application.js');
const System = require('../modules/System.js');

class GrowtopiaHelper extends EventEmitter {
constructor(){
super();
// Growtopia client status
this.clientIsOpen = false;

// The timestamp the user started playing on
this.startedPlaying = new Date();

// Whether or not location is turned off
this.jammed = false;
this.appData = Application.device.isMacOS ? `${process.env.HOME}/Library/Application Support/growtopia` : `${process.env.APPDATA}\\..\\Local\\Growtopia`;
this.splitter = Application.device.isMacOS ? '/' : `\\`

fs.watchFile(`${this.appData}${this.splitter}save.dat`, (curr, prev) => {
// App data path
this.appData = System.os.isMacOS ? `${process.env.HOME}/Library/Application Support/growtopia/` : `${process.env.APPDATA}\\..\\Local\\Growtopia\\`;

// Start watching save.dat for updates
fs.watchFile(`${this.appData}save.dat`, (curr, prev) => {
this.emit("saveDatUpdate");
});
}

async isOpen(){
if(Application.device.isMacOS) return await this.isOpenMacOS();
else return await this.isOpenWindows();
}

async isOpenWindows(){
return new Promise((resolve, reject) => {
exec('tasklist', (err, stdout, stderr) => {
if(!stdout) resolve(false);
resolve(stdout.includes("Growtopia.exe"));
});
});
return await System.processExists('Growtopia', ['Growtopia', 'Growtopia.exe']);
}

async isOpenMacOS(){
return new Promise((resolve, reject) => {
let isFound = findProcess('name', 'Growtopia').then(list => {
for (let process of list) {
if (process.name === 'Growtopia') {
resolve(true);
}
}
resolve(false);
})
});
}

checkAppStatus(){
async checkAppStatus(){
let self = this;
(async function check(){
let clientIsOpen = await self.isOpen();
Expand All @@ -65,7 +49,7 @@ class GrowtopiaHelper extends EventEmitter {

async readSaveDat(){
return new Promise((resolve, reject) => {
fs.readFile(`${this.appData}${this.splitter}save.dat`, 'utf8' , (err, data) => {
fs.readFile(`${this.appData}save.dat`, 'utf8' , (err, data) => {
if(err){
return reject(err);
}
Expand All @@ -76,9 +60,15 @@ class GrowtopiaHelper extends EventEmitter {

async getSaveDatItem(key){
return new Promise((resolve, reject) => {
this.readSaveDat().then(data => {
this.readSaveDat()
.then(data => {
// If key does not exist, return false
if(data.indexOf(key) < 0) resolve(false);

// Return the key's value
resolve(data[data.indexOf(key)+1]);
}).catch(e=>reject(e));
})
.catch(e=>reject(e));
});
}

Expand Down
28 changes: 28 additions & 0 deletions modules/System.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const fetch = require('node-fetch');
const findProcess = require('find-process');
const EventEmitter = require('events');
const os = require('os');

class System {
constructor(){
this.os = {
name: os.platform(),
isWindows: os.platform() === 'win32',
isMacOS: os.platform() === 'darwin',
splitter: os.platform() === 'darwin' ? '/' : `\\`
};
}

async processExists(wildcard, processes = false){
return new Promise((resolve, reject) => {
if(!processes) processes = [wildcard];
else if(!Array.isArray(processes)) processes = [processes];

findProcess('name', wildcard).then(list => {
resolve(list.filter(l => processes.includes(l.name)).length > 0);
});
});
}
}

module.exports = new System();
2 changes: 1 addition & 1 deletion package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "growtopia-discord-presence",
"version": "1.5.2",
"version": "1.6.3",
"description": "Growtopia Discord Rich Presence by GrowStocks",
"main": "index.js",
"scripts": {
Expand Down

0 comments on commit 7e2d5b1

Please sign in to comment.