Skip to content

Commit

Permalink
Merge pull request #13 from T0biasCZe/Rewrite-Discord-RPC-init/deinit
Browse files Browse the repository at this point in the history
Rewrite discord rpc init/deinit
  • Loading branch information
T0biasCZe authored Sep 28, 2024
2 parents 115362e + 2f75e01 commit 40bff09
Show file tree
Hide file tree
Showing 8 changed files with 186 additions and 83 deletions.
5 changes: 4 additions & 1 deletion Discord WMP/AlbumArtAdder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,9 @@ private void showinlistbox() {
else if(pér.type == pairtype.titlecontains) {
listBox1.Items.Add(pér.filename + " ;;; " + pér.contains + " ;;; " + pér.doesntcontain + "\t" + pér.priority + "\t (words contained in title name)");
}
else if(pér.type == pairtype.audiofilenamecontains) {
listBox1.Items.Add(pér.filename + " ;;; " + pér.contains + " ;;; " + pér.doesntcontain + "\t" + pér.priority + "\t (words contained in audiofile name)");
}
else if(pér.type == pairtype.artistname) {
listBox1.Items.Add(pér.filename + " ;;; " + pér.contains + " ;;; " + pér.doesntcontain + "\t" + pér.priority + "\t (artists name)");
}
Expand Down Expand Up @@ -190,7 +193,7 @@ private void AlbumArtAdder_SizeChanged(object sender, EventArgs e) {
}
}
//create int enum "pairtype" with names "albumstring", "albumcontains" and "titlecontains"
public enum pairtype : int {albumstring, albumcontains, titlecontains, audiofilename, artistname};
public enum pairtype : int {albumstring, albumcontains, titlecontains, audiofilename, artistname, audiofilenamecontains};
public struct pair {
public string filename { get; set; }
public pairtype type { get; set; }
Expand Down
3 changes: 3 additions & 0 deletions Discord WMP/App.config
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@
<setting name="first_setup" serializeAs="String">
<value>True</value>
</setting>
<setting name="dont_hide" serializeAs="String">
<value>False</value>
</setting>
</Discord_WMP.Settings1>
</userSettings>
<runtime>
Expand Down
5 changes: 4 additions & 1 deletion Discord WMP/Form1.Designer.cs

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

188 changes: 113 additions & 75 deletions Discord WMP/Form1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public partial class Form1 : Form {
private bool show_console;
private bool use_rpc;
public DiscordRpcClient client;
public static int random_port;
public static int random_port = 42565;
public static bool albummanageropen = false;

[DllImport("kernel32.dll")]
Expand All @@ -66,6 +66,49 @@ private void SmoothingText_Paint(object sender, PaintEventArgs e) {
}

public Form1() {
//check if app is already running by sending http request to "localhost:42565/alive"
bool appAlreadyRunning = false;
try {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:42565/alive");
request.Timeout = 2000;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if(response.StatusCode == HttpStatusCode.OK) {
appAlreadyRunning = true;
}
}
catch(WebException) {

}
if(!appAlreadyRunning) { //app unresponsive or not running, so kill it
Process[] processes = Process.GetProcessesByName("Discord WMP");
foreach(Process process in processes) {
if(process.Id == Process.GetCurrentProcess().Id) continue;
process.Kill();
}
}

if(appAlreadyRunning) {
if(Environment.GetCommandLineArgs().Contains("getdata")){
//send http request to "localhost:42565/getdata" to get data
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:42565/info");
request.Timeout = 1000;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if(response.StatusCode == HttpStatusCode.OK) {
//get data from response
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
//send data to console
Console.WriteLine(responseFromServer);
//close response
response.Close();
//close app
Environment.Exit(0);
}
}
else Environment.Exit(0);
}

if(Settings1.Default.first_setup) {
loadingsettings = true;
DialogResult dialog_userpc = MessageBox.Show("Do you want to put WMP play data into Discord Rich presence?\n(Recommended YES if you have Discord installed)", "Initial setup", MessageBoxButtons.YesNo);
Expand All @@ -87,7 +130,7 @@ public Form1() {
// Show console during boot
ShowWindow(handle, SW_SHOW);

Random random = new Random();
/*Random random = new Random();
bool isAvailable = false;
while(isAvailable == false) {
random_port = random.Next(49152, 65535);
Expand All @@ -104,7 +147,7 @@ public Form1() {
isAvailable = true;
}
}
}
}*/
Console.SetWindowSize(50, 15);
InitializeComponent();

Expand Down Expand Up @@ -195,6 +238,7 @@ private void settingsload() {
checkBox_sendMediaInfo.Checked = send_media_info;
use_rpc = Settings1.Default.show_discord;
checkBox_userpc.Checked = use_rpc;
checkBox_dontautohide.Checked = Settings1.Default.dont_hide;

Console.WriteLine("loaded settings");
loadingsettings = false;
Expand All @@ -218,6 +262,7 @@ private void checkBox_changed(object sender, EventArgs e) {
Settings1.Default.show_console = show_console;
use_rpc = checkBox_userpc.Checked;
Settings1.Default.show_discord = use_rpc;
Settings1.Default.dont_hide = checkBox_dontautohide.Checked;

var handle = GetConsoleWindow();
if(show_console) ShowWindow(handle, SW_SHOW);
Expand Down Expand Up @@ -248,6 +293,11 @@ private void button_settings_Click(object sender, EventArgs e) {
this.Height = 428;
}
}
private void linkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
string URL = ((LinkLabel)sender).Links[0].LinkData.ToString();
Console.WriteLine(URL);
System.Diagnostics.Process.Start(URL);
}

public struct playback_data {
public string title;
Expand All @@ -266,6 +316,7 @@ public struct playback_data {
public string path;
public string media_type;
}
//gets current information from Windows Media Player
public playback_data Data() {
playback_data data = new playback_data();
data.artist = ""; data.album = ""; data.title = ""; data.lenght = ""; data.position = ""; data.lenght_sec = -1; data.position_sec = -1; data.play_state = WMPLib.WMPPlayState.wmppsStopped; data.guid = ""; data.path = "";
Expand Down Expand Up @@ -328,15 +379,27 @@ public playback_data Data() {
abort:;
return data;
}

//displays the current information from Windows Media Player
private void debug(playback_data data) {
label3.Text = "initialized " + initialized.ToString();
label4.Text = "send_data_lasttime " + send_data_lasttime.ToString();
label5.Text = "play_state " + data.play_state.ToString();
label6.Text = "mediatype " + data.media_type;
label7.Text = "audiofilename " + data.audiofilename;

}
public static bool check_discord_running() {
//check if executable discord.exe, discordcanary.exe or discordptb.exe is running
Process[] pname = Process.GetProcessesByName("discord");
Process[] pname2 = Process.GetProcessesByName("discordcanary");
Process[] pname3 = Process.GetProcessesByName("discordptb");
bool discordrunning = !(pname.Length == 0 && pname2.Length == 0 && pname3.Length == 0);
Console.BackgroundColor = ConsoleColor.Cyan;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Discord running: " + discordrunning);
Console.ResetColor();
return discordrunning;
}

bool initialized = false;
bool send_data_lasttime = false;
Stopwatch pause_stopwatch = new Stopwatch();
Expand All @@ -346,12 +409,6 @@ private void update_Tick(object sender, EventArgs e) {
if(data.lenght_sec == -1 || data.position_sec == -1) {
playeddata = "Couldnt find WMP";
this.Refresh();
if(use_rpc && initialized && send_data_lasttime) {
client.SetPresence(new RichPresence());
send_data_lasttime = false;
Deinitialize();
initialized = false;
}
}
bool stopped = data.play_state.In(WMPLib.WMPPlayState.wmppsStopped, WMPLib.WMPPlayState.wmppsMediaEnded, WMPLib.WMPPlayState.wmppsUndefined);
if(data.play_state == WMPPlayState.wmppsPaused) {
Expand All @@ -369,18 +426,31 @@ private void update_Tick(object sender, EventArgs e) {
if(stopped) {
playeddata = "Stopped";
this.Refresh();
if(use_rpc && initialized && send_data_lasttime) {
client.SetPresence(new RichPresence());
send_data_lasttime = false;
Deinitialize();
initialized = false;
Console.WriteLine("stopped and deinitialized");
}
}
if(send_media_info) {
systemMediaControls.update(data, this);
}
if(use_rpc && !stopped) {
if(!check_discord_running()) {
if(initialized) {
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Discord not running but RPC inited, deiniting");
Console.ResetColor();
Deinitialize();
initialized = false;
}
}
else {
if(!initialized) {
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("RPC Client not initialized, initing");
Initialize();
initialized = true;
Console.WriteLine("Initialized Discord RPC");
Console.ResetColor();
}
}

var mil = data.position_sec / data.lenght_sec;
var time = data.position + "/" + data.lenght;
var playbar = progressbar(mil, 10);
Expand All @@ -393,47 +463,8 @@ private void update_Tick(object sender, EventArgs e) {
playeddata += "\n" + albumart;
this.Refresh();

bool discord_not_running = false;
/*try {
}
catch {
Console.WriteLine("discord not running");
discord_not_running = true;
}*/
Console.WriteLine("e");
label8.Text = "discord_not_running " + discord_not_running.ToString();
if(discord_not_running) {
if(initialized) {
Deinitialize();
initialized = false;
Console.WriteLine("discord not running, deinitialized");
}
goto breakout;
}
if(!initialized) {
try {
if(client_id != null && client_id.Text.Length >= 3) {
Console.WriteLine("valid client id");
bool result = Initialize();
if(result) {
Console.WriteLine("initialized");
initialized = true;
}
else {
Console.WriteLine("error initializing RPC.");
initialized = false;
goto breakout;
}
}
}
catch {
ConsoleColor old = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("error initializing RPC. Discord propably not running.\n If you do not want to use Discord RPC disable it in checkboxes below");
Console.ForegroundColor = old;
goto breakout;
}
}
if(!initialized) return;

client.SetPresence(new RichPresence() {
Details = data.title.Truncate(32),
State = data.artist.Truncate(32),
Expand All @@ -452,25 +483,38 @@ private void update_Tick(object sender, EventArgs e) {
send_data_lasttime = true;
Console.WriteLine("set data");
}
else if(!use_rpc && initialized) {
if(send_data_lasttime && initialized && stopped) {
client.ClearPresence();
}
if(!use_rpc && initialized) {
client.ClearPresence();
Deinitialize();
initialized = false;
}
breakout:;
}
}

bool Initialize() {
/*
Create a Discord client
NOTE: If you are using Unity3D, you must use the full constructor and define
the pipe connection.
*/
Console.BackgroundColor = ConsoleColor.Cyan;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Initialize() ran");
Console.ResetColor();

if(client_id.Text.Length <= 8) {
Console.WriteLine("invalid client id");
return false;
}
client = new DiscordRpcClient(client_id.Text);
if(client != null) {
try {
client.Deinitialize();
client.Dispose();
}
catch {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Error while deinitializing client while initializing client");
Console.ResetColor();
}
}
client = new DiscordRpcClient(client_id.Text, -1);

//Set the logger
client.Logger = new ConsoleLogger() { Level = LogLevel.Warning };
Expand All @@ -481,7 +525,7 @@ the pipe connection.
};

client.OnPresenceUpdate += (sender, e) => {
//Console.WriteLine("Received Update! {0}", e.Presence);
Console.WriteLine("Received Update! {0}", e.Presence);
};

//Connect to the RPC
Expand All @@ -490,12 +534,6 @@ the pipe connection.
}
void Deinitialize() {
client.Deinitialize();
client.OnPresenceUpdate -= (sender, e) => {
//Console.WriteLine("Received Update! {0}", e.Presence);
};
client.OnReady -= (sender, e) => {
Console.WriteLine("Received Ready from user {0}", e.User.Username);
};
client.Dispose();
}
private string progressbar(double value, int lenght) {
Expand Down
Loading

0 comments on commit 40bff09

Please sign in to comment.